2016-12-29 109 views
1

我想創建一個.so文件並讓main.cpp文件可以從.so文件中調用該函數。關於Linux .so文件無法鏈接到main.cpp文件

而這些是我的文件。

//aa.h 
#include <stdio.h> 
#include <stdlib.h> 
void hello(); 

//hola.c 
#include <stdio.h> 
#include "aa.h" 
void hello() 
{printf("Hello world!\n");} 

//main.cpp 
#include "aa.h" 
void hello(); 
int main(){hello();return 0;} 

這是下面的步驟。

第1步:創建.so文件

$ gcc hola.c -fPIC -shared -o libhola.so 

它的工作原理

第2步:連接到libhola.so到的main.cpp並創建一個名爲測試

$ gcc main.cpp -L. -lhola -o test 

一個執行文件只是我試過的兩步。

和錯誤說:

main.cpp:(.text+0x12): undefined reference to `hello()' 
collect2: error: ld returned 1 exit status 

我已經試過了移動libhola.so到/ usr/lib和移動aa.h到/ usr/inclued,但不起作用。

+0

如果我是正確的,頭文件應包含'的#ifndef SOME_NAME 的#define SOME_NAME //做一些事情 #endif' – Shravan40

+1

C++語言軋液的所有函數名,包括返回類型和參數類型。 C語言不這樣做。 'gcc'編譯器不用於編譯/鏈接C++代碼。改爲使用'g ++'或'gpp'。獲取C++主程序來處理庫中的函數'hello',庫的頭文件必須包含#ifdef cplusplus {....},這個函數包含'hello'函數的原型。請注意,由於'hello'的原型位於頭文件中,因此不要在'main.c'文件 – user3629249

+0

中從cmd提示符處調用'ldconfig'重複該原型。還要檢查'ldconfig -p | grep「hola」給出了一些結果。 – sameerkn

回答

2

您正在將共享庫編譯爲C文件(特別是hello()函數),但您在編譯C++源代碼時將其鏈接。您需要確保hello()可以從C++可執行文件調用(即不是name mangled)。

在頭 aa.h

即添加extern "C"

#ifdef __cplusplus 
extern "C" { 
#endif 
void hello(); 

#ifdef __cplusplus 
} 
#endif 

我建議增加一個include guard了。

或者,如果您將main.cpp重命名爲main.c,那麼在沒有這個的情況下它會很好地編譯。