conflicts with new declaration with 'C' linkage错误修改

                         

 


在c++程序中调用C编写的库,源代码如下

一共有三个文件ms.h ms.c main.cpp 其中ms.h和ms.c编为一个动态库

/*ms.h 代码*/

21 typedef struct sip
22 {
23     int fd ;
24 }VSIP;
25
26 struct sip testlink[10];
27
28
29 int dprint(int pa);

/*ms.c代码*/

20 #include "stdio.h"
21 #include "stdlib.h"
22 #include "string.h"
23 #include "ms.h"
24
25 int dprint(int pa)
26 {
27     testlink[0].fd = pa;
28     printf("test int = %d\n",testlink[0].fd);
29     return 0;
30 }
31

编译为一个动态库:

gcc -shared -fPIC -o libtest.so ms.c

/*main.cpp*/

  18 #include <stdio.h>
19 #include <stdlib.h>
20 #include "ms.h"
21
22 extern "C"
23 {
24  int  dprint(int pa);
25  extern struct sip testlink[];
26 }
27
28
29
30 int  main()
31 {
32     int p = 100;
33     dprint(p);
34     return 0;
35 }
36

编译:

g++ -o main -ltest -L. main.cpp
报错如下:

ms.h:29: error: previous declaration of 'int dprint(int)' with 'C++' linkage
main.cpp:24: error: conflicts with new declaration with 'C' linkage
ms.h:26: error: previous declaration of 'sip testlink [10]' with 'C++' linkage
main.cpp:25: error: conflicts with new declaration with 'C' linkage

错误分析:

在main.cpp中如果已经包含了ms.h就不必再用extern “C”去声明了。

如果不包含ms.h则用extern “c”声明即可


【yasi】另外注意:

 
  1. extern "C"
  2. ... 
上面的一对大括号中,不要出现C++的语句,比如

 
  1. #include <string> 
  2. using namespace std; 

你可能感兴趣的:(conflicts with new declaration with 'C' linkage错误修改)