C调用C++代码

语言: CN / TW / HK

有时C程序里需要用到C++的类,但是C语言又不能直接调用类,这时需要把C++的类使用C接口封装后,再调用,

可以将封装后的C++代码编译成库文件,供C语言调用;

需要注意的是,封装的C++代码库文件是用g++编译的,所以在C中调用时,需要添加extern "C"{}关键字。

编译c代码时,要加上-lstdc++

如下代码,是c代码使用C++的map容器的例子:

``` //test.cpp 封装C++代码

include

include

include "test.h"

using namespace std;

static map m_testMap;

void pushVal(int key, int val) { m_testMap[key] = val; }

int getVal(int key) { map::iterator iter = m_testMap.find(key); if (iter != m_testMap.end() ) { return iter->second; }

return  -1;

}

//头文件 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

endif

```

main函数,调用封装的C++接口:

``` //main.c

include

include "test.h"

int main() { printf("test\n"); for (int i = 0; i < 10; i++) { printf("push key: %d, val: %d\n", i, i10); pushVal(i, i10); }

int val = 0;
for (int i = 0; i < 10; i++)
{
    val = getVal(i);
    printf("get key: %d, val: %d\n", i,val);
}
return 0;

} ```

编译的时候,为了简单,我这里没有编译成库文件,直接用引用.o编译的:

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 ```

编译运行结果如下:

``` 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++

运行: ./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: 90 ```

个人微信服务号同步推送文章(微信公众号:fensnote):