2013-01-07 52 views
0

我想链接我的程序中已经存在的库。我的程序是用C++编写的,而库是用C开发的。现在,我在编译和链接时遇到了问题。将gcc与g ++代码连接起来

我跟着这个论坛的许多帖子,有关链接gcc库与g ++源。不知何故,我可以解决一些问题。现在,我面临着一个问题。这是我的问题的细节。

在testlib.h文件

int sum(int x, int y) 

In testlib.c file 

int sum(int x, int y) { 
    return x + y; 
} 

我创建这些文件的静态库。

我的下一步是在g ++源代码中使用这个函数。

在call.hh文件,

#include<iostream> 


#include "testlib.h" 

using namespace std; 

extern "C" { 
    int sum(int x, int y); 
} 

namespace math_operation { 
    void show_addition(int x, int y); 
} 

我call.cc文件中定义该功能现在

#include "call.hh" 
#include<iostream> 

using namespace std; 

void math_operation::show_addition(int x, int y){ 
    cout<<" sum "<<sum(x, y)<<endl; 
} 

,我称之为main.cc

#include "call.hh" 

using namespace math_operation; 
int main() { 
    int x = 10; 
    int y = 15; 
    show_addition(x, y); 
    return 0; 
} 

此功能我有两个问题: 首先,它给出了编译错误,因为我已经声明了函数int sum(int,int)两次。但是如果我在call.hh中没有声明extern“C”{int sum(int,int)},编译问题就解决了,并且连接器问题被创建并带有以下错误: 未定义引用'sum(int,int) '

我该如何解决?

回答

3
extern "C" { 
#include "testlib.h" 
} 

并且不要自己声明。应该管用。

+0

它给冲突错误。 – Exchhattu

+3

'gcc -c testlib.c -o testlib.o; g ++ main.cc call.cc testlib.o -o main'工作。 – aragaer

0

对于testlib.h是在C++文件中使用它应该申报的功能extern "C":当你定义sumextern "C"定义声明匹配,则

#ifdef __cplusplus 
extern "C" { 
#endif 

int sum(int x, int y); 

#ifdef __cplusplus 
} 
#endif 

,和你没有得到任何一个重新声明错误或未定义的参考。

如果您不能编辑testlib.h则可以将其包含一个extern "C"块内,作为aragaer的回答显示:

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

(但是这通常是一个哈克解决方法,它是更好地解决库)

在自己call.hh文件,则不应申报sum,有声明它的标题,你应该使用的标题(添加extern "C"头内部或周围的#include如果需要的话)