2015-09-09 40 views
0

这是我一直在收到的错误。C++中的未定义引用

-bash-4.1$ g++ strl.cpp -o -lc- 
/tmp/ccRpiglh.o: In function `main': 
strl.cpp:(.text+0xf): undefined reference to `plusplus' 
collect2: ld returned 1 exit status 

听说是strl.cpp的源代码。这是一个重复我的问题的简单例子。

strl.cpp 
#include <iostream> 
#include <stdlib.h> 
#include "libc-.h" 

using namespace std; 

int main() 
{ 
    cout<<plusplus(5,2)<<'\n'; 
} 

这里是源libc.cpp

libc.cpp 
#include <iostream> 

using namespace std; 

int plusplus(int a, int b) 
{ 
    return a + b; 
} 

来源为的libc-.H

libc-.h 
#ifndef _SCANTYPE_H_ 
#define _SCANTYPE_H_ 

#include <iostream> 
#include <stdlib.h> 

#ifdef __cplusplus 
extern "C" 
{ 
#endif 

    using namespace std; 

    int plusplus(int a, int b); 

#ifdef __cplusplus 
} 
#endif 

#endif 

我与编译如下:

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp 
g++ strl.cpp -o -lc- 

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp编译没有错误。

为什么函数plusplus是未定义的引用?

感谢您对我做错什么的看法。

+0

可能重复[什么是未定义的引用/未解析的外部符号错误,以及如何解决它?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-外部符号错误和如何-DO-修复) – Niall

回答

0

围绕函数定义您不需要extern C吗?我敢打赌,链接器正在试图将非法C名称与非法C名称进行匹配。

并注意您正在使用C++功能(using),因此检查#ifdef cplusplus是多余的。如果它是错误的,你的编译将失败。

0

plusplus()的引用缺失,因为它没有提供。您在libc-.h看好

`int plusplus(int a, int b);` 

C联动,但不守诺言的libc.cpp。 要解决该问题,后者的文件来

// libc.cpp 
#include <iostream> 
#include "libc-.h" // include proto-type which has C linkage 

int plusplus(int a, int b) 
{ 
    return a + b; 
} 

此外,你应该永远头文件做using namespace std;