【发布时间】:2016-04-15 15:45:49
【问题描述】:
我遇到了无法将 stdc++ 库编译到我的 c 程序中的问题。我在 Ubuntu 14.04,gcc 4.9 上。
我的问题是:是否可以在 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
很抱歉,如果这是重复的,但我找不到这样的问题。
【问题讨论】:
-
更改
cppfile.h以有效读取extern "C" int myFunction();以使用#ifdef __cplusplus保护进行 C++ 编译(就像在系统中包含/usr/include中的文件一样)以免你#includecppfile.h标题中的C++ 文件并以 another 集undefined reference错误结束。如果您不这样做,任何尝试调用myFunction()的 C++ 代码都会尝试找到 the mangled symbol name。 -
1) 分别编译每个 *.c 文件,不要试图在同一行编译和链接。 (注意:在同一行编译/链接是可能的,但需要正确执行) 2) gcc 链接器按照它们出现的顺序处理命令行参数,从左到右。当它处理
-l参数时,它还没有需要解析的未解析引用。按顺序写链接命令行:gcc <options> cppfile.o cfile.o -lstdc++ -
在编译/链接时,请记住 C++ 会破坏所有函数的名称。因此,编译步骤需要生成函数名称被破坏的目标文件