linux c++调用c

参考 【Linux下gcc编译的四个过程】_Deacde_ZY的博客-优快云博客

C与C++如何互相调用_c文件引用c++头文件_卍一十二画卍的博客-优快云博客

Linux动态链接库的创建与使用_linux创建动态库_满天星羽的博客-优快云博客

 c++调用c

1.1 

例子1: test1.c

#include <stdio.h>
//#include "test1.h"
void hello()
{
   printf("hello world  11\n");

}

例子2:  直接在.cpp文件里面  使用extern "C"

///#include "test1.h"

extern "C" 
{
extern  void hello();
}

int  main()
{

hello();

}

编译:g++ test1.c test2.cpp -o test88 报如下error

原因: test1.c 并没有说明test1.c 里面的函数按照c的方式编译,而在test2.cpp里面是按照c的格式来使用。正确的方法应该分开编译,然后再链接:

gcc -c test1.c  -o test1.o   // 1   参数-c 表示编译但不链接 这里只能用gcc 编译

g++ -c test2.cpp -o test2.o  // 2  编译不链接

g++ test2.cpp test1.o  test  //3   链接所有.o  

注意:步骤2,3 可以综合成  g++ test2.cpp test1.o -o test 

1.2 改进: 增加test1.h 文件,去除在test2.cpp 里面直接引用,改为使用test1.h头文件

test1.h

extern "C" 
{
extern void hello();
}

改进后的test2.cpp  使用头文件

#include "test1.h"

int  main()
{

hello();

}

编译:

gcc -c test1.c  -o test1.o   // 1   参数-c 表示编译但不链接 这里只能用gcc 编译

g++ test2.cpp test1.o -o test 

改进3:test1.c 包含test1.h  g++编译test1.c时,在编译时先对test1.h 进行了预处理。仍然按照c的方式编译。

test1.c

#include <stdio.h>
#include "test1.h"
void hello()
{
   printf("hello world  11\n");

}
编译:一步到位

g++ test1.c test2.cpp -o  test

c++ 调用c的惯用方法: 在 .cpp文件中 加入 extern "C " { #include "test1.h"}

test1.h
extern void hello(); 
当作为动态库给外部模块使用时 必须要加 extern
 

 test1.c

#include <stdio.h>
void hello()
{
   printf("hello world  11\n");

}

例子2:  直接在.cpp文件里面  使用extern "C"

extern "C" 
{
#include "test1.h"
}

int  main()
{

hello();

}

编译:两步走

 gcc -c test1.c -o test1.o
 g++ test2.cpp  test1.o -o  test
 

这种方法的优点是 不用对原来的c文件或c开源库做任何的改动. 推荐。

1.3 编译动态库和使用

-fPIC 或 -fpic 参数的作用是使得 gcc 生成的代码是与位置无关的,也就是使用相对位置。

-shared参数的作用是告诉编译器生成一个动态链接库

gcc test1.c -shared -fpic -o libtest1.so   // 生成动态库 -fpic 生成位置无关的代码

g++ test2.cpp  -L . -ltest1  -o testcpp
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值