2015-09-09 38 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;