Sometimes C programs need to use C++ classes, but C language can not directly call the class, then need to use C interface encapsulation C C class, and then call.

Can be encapsulated C++ code compiled into a library file for C language call;

Note that the wrapped C++ code base file is compiled with g++, so the extern “C”{} keyword needs to be added when called from C.

When compiling C code, add -lstDC ++

 

The following code is an example of c code using c ++ map:

//test. CPP encapsulates C++ code #include <map> #include <iostream> #include "test.h" using namespace STD; static map<int, int> m_testMap; void pushVal(int key, int val) { m_testMap[key] = val; } int getVal(int key) { map<int, int>::iterator iter = m_testMap.find(key); if (iter ! = m_testMap.end() ) { return iter->second; } return -1; } // header file test.h #ifndef _TEST_H_ #define _TEST_H_ #ifdef __cplusplus extern "C" {#endif void pushVal(int key, int val); int getVal(int key ); #ifdef __cplusplus } #endif #endifCopy the code

The main function calls the encapsulated C++ interface:

//main.c

#include <stdio.h>
#include "test.h"



int main()
{
	printf("test\n");
	for (int i = 0; i < 10; i++)
	{
		printf("push key: %d, val: %d\n", i, i*10);
		pushVal(i, i*10);
	}
	
	int val = 0;
	for (int i = 0; i < 10; i++)
	{
		val = getVal(i);
		printf("get key: %d, val: %d\n", i,val);
	}
	return 0;
}
Copy the code

When compiling, for the sake of simplicity, I do not compile into the library file, directly use the.o compilation:

The makefile:

all: 
	g++ -Wall -c  test.cpp -o test.o
	gcc -Wall -c  main.c -o main.o

	gcc -Wall test.o main.o -o test -lstdc++

clean:
	rm test *.o
Copy the code

The compilation results are as follows:

Make g++ -wall -c test.cpp -o test.o GCC -wall -c main.c -o main.o GCC -wall test.o main.o -o test -lstdc++ run:  ./test test push key: 0, val: 0 push key: 1, val: 10 push key: 2, val: 20 push key: 3, val: 30 push key: 4, val: 40 push key: 5, val: 50 push key: 6, val: 60 push key: 7, val: 70 push key: 8, val: 80 push key: 9, val: 90 get key: 0, val: 0 get key: 1, val: 10 get key: 2, val: 20 get key: 3, val: 30 get key: 4, val: 40 get key: 5, val: 50 get key: 6, val: 60 get key: 7, val: 70 get key: 8, val: 80 get key: 9, val: 90Copy the code

Synchronously push articles by personal wechat service account (wechat public account: Fensnote) :