2016-04-15 60 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