2016-04-15 91 views
0

我有一個無法在stdC++庫中編譯進我的c程序的問題。我在Ubuntu 14.04上,gcc 4.9。在'c'程序中使用gcc/g ++編譯stdC++的問題

我的問題是:是否有可能在stdC++編譯成c程序。這也可以使用armhf-linux交叉編譯器/庫來完成嗎?

我使用下面的命令行編譯:

g++ -c cppfile.cpp 
gcc -o cfile -lstdc++ cppfile.o cfile.c 

我還用G ++而不是GCC嘗試,但我得到了同樣的錯誤。

我的主要文件是:

// cfile.c 
#include <string.h> 
#include <stdio.h> 
#include "cppfile.h" 

int main() 
{ 
    printf("Hello"); 
    myFunction(); 

    return 0; 
} 

我的C++文件是在這裏:

// cppfile.cpp 
#include <string> 

using namespace std; 

extern "C" { 
int myFunction() 
{ 
    std::string s = "hi"; 
    return 1; 
} 
} 

頭文件:

// cppfile.h 
int myFunction(); 

該編譯輸出如下:

cppfile.o: In function `myFunction': 
cppfile.cpp:(.text+0xf): undefined reference to `std::allocator<char>::allocator()' 
cppfile.cpp:(.text+0x27): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)' 
cppfile.cpp:(.text+0x36): undefined reference to `std::allocator<char>::~allocator()' 
cppfile.cpp:(.text+0x4a): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' 
cppfile.cpp:(.text+0x5f): undefined reference to `std::allocator<char>::~allocator()' 
cppfile.o:(.eh_frame+0x13): undefined reference to `__gxx_personality_v0'  collect2: error: ld returned 1 exit status 

對不起,如果這是重複的,但我找不到這樣的問題。

+0

變化'cppfile.h'有效閱讀'的extern 「C」 INT myFunction的();'爲C++編譯使用'#ifdef來__cplusplus'衛士(就像在系統包括文件放在/ usr/include中),以免你在C++文件中包含你的'cppfile.h'頭文件,並且結束*另外一組未定義的引用錯誤。如果你不這樣做,任何試圖調用'myFunction()'的C++代碼都會嘗試查找[mangled symbol name](https://en.wikipedia.org/wiki/Name_mangling#C.2B.2B )。 –

+0

1)分別編譯每個* .c文件,不要嘗試在同一行編譯和鏈接。 (注意:可以在同一行編譯/鏈接,但需要正確執行)2)gcc鏈接器按照從左到右的順序處理命令行參數。當它處理'-l'參數時,它還沒有未解析的引用需要解析。編寫鏈接命令行的順序如下:'編譯/鏈接時,'gcc cppfile.o cfile.o -lstdC++' – user3629249

+0

,請記住C++會壓縮所有函數的名稱。所以編譯步驟將需要導致函數名稱變形的目標文件 – user3629249

回答

0

這應該工作:

g++ -c cppfile.cpp 
gcc -c cfile.c 
g++ -o cfile cppfile.o cfile.o