
有时C程序里需要用到C的类但是C语言又不能直接调用类这时需要把C的类使用C接口封装后再调用可以将封装后的C代码编译成库文件供C语言调用需要注意的是封装的C代码库文件是用g编译的所以在C中调用时需要添加extern C{}关键字。编译c代码时要加上-lstdc如下代码,是c代码使用C的map容器的例子1234567891011121314151617181920212223242526272829303132333435363738394041424344454647//test.cpp 封装C代码#include map#include iostream#include test.husingnamespacestd;staticmapint,int m_testMap;voidpushVal(intkey,intval){m_testMap[key] val;}intgetVal(intkey){mapint,int::iterator iter m_testMap.find(key);if(iter ! m_testMap.end() ){returniter-second;}return-1;}//头文件 test.h#ifndef _TEST_H_#define _TEST_H_#ifdef __cplusplusexternC{#endifvoidpushVal(intkey,intval);intgetVal(intkey );#ifdef __cplusplus}#endif#endifmain函数调用封装的C接口123456789101112131415161718192021222324//main.c#include stdio.h#include test.hintmain(){printf(test\n);for(inti 0; i 10; i){printf(push key: %d, val: %d\n, i, i*10);pushVal(i, i*10);}intval 0;for(inti 0; i 10; i){val getVal(i);printf(get key: %d, val: %d\n, i,val);}return0;}编译的时候为了简单我这里没有编译成库文件直接用引用.o编译的makefile12345678all:g -Wall -c test.cpp -o test.ogcc -Wall -c main.c -o main.ogcc -Wall test.o main.o -o test -lstdcclean:rm test *.o编译运行结果如下1234makeg -Wall -c test.cpp -o test.ogcc -Wall -c main.c -o main.ogcc -Wall test.o main.o -o test -lstdc运行./testtestpush key: 0, val: 0push key: 1, val: 10push key: 2, val: 20push key: 3, val: 30push key: 4, val: 40push key: 5, val: 50push key: 6, val: 60push key: 7, val: 70push key: 8, val: 80push key: 9, val: 90get key: 0, val: 0get key: 1, val: 10get key: 2, val: 20get key: 3, val: 30get key: 4, val: 40get key: 5, val: 50get key: 6, val: 60get key: 7, val: 70get key: 8, val: 80get key: 9, val: 90到此这篇关于C调用C代码的方法步骤的文章就介绍到这了