c++ - Windows 7 上的 C++ 程序中的链接器错误

标签 c++

我只是想尝试编译器选项,但出现链接器错误。通过 MinGW 在 Windows 7 上使用的 g++ 是 4.7.2

代码是一个名为test.cpp的简单测试代码:

#include <iostream>
#include <cstdlib>
using namespace std;

#define max 10

int main()
{
 int a;
 int arr[max];
 cout<<"this is the sample text"<<endl;
 system("pause");
}

现在我开始一步步编译:

1.cpp test.cpp>test.i
2.g++ -S test.i
3.as -o test.o test.s
4.ld -o test.exe test.o

前三步没问题,最后一步出现以下错误:

test.o:test.cpp:(.text+0x12): undefined reference to `__main'
test.o:test.cpp:(.text+0x21): undefined reference to `std::cout'
test.o:test.cpp:(.text+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
test.o:test.cpp:(.text+0x2d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
test.o:test.cpp:(.text+0x34): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
test.o:test.cpp:(.text+0x43): undefined reference to `system'
test.o:test.cpp:(.text+0x52): undefined reference to `_Unwind_Resume'
test.o:test.cpp:(.text+0x6a): undefined reference to `std::ios_base::Init::~Init()'
test.o:test.cpp:(.text+0x8b): undefined reference to `std::ios_base::Init::Init()'
test.o:test.cpp:(.text+0x97): undefined reference to `atexit'
ld: test.o: bad reloc address 0x0 in section `.ctors'
ld: final link failed: Invalid operation

最佳答案

您的问题是您没有将所需的库(例如标准 C++ 库)和其他目标文件传递给 ld

我不在 windows 上工作,但我认为这样做很简单:

g++ test.cpp -o test

应该可以。 g++ 自动为您进行预处理和链接。

关于c++ - Windows 7 上的 C++ 程序中的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33322050/

相关文章:

c++ - 带有 cuda 的简单 C++ HelloWorld

c++ - 用于 Metro 风格应用程序的 HTML/CSS 渲染器

c++ - 简单的 x86-64 C++ 内联汇编 "Hello World"示例

c++ - Qt如何检查按下了哪个鼠标按钮

c++ - 重载 << 使用模板 : Why am I getting the following error?

c++ - 在 MSVC 中编译 constexpr 代码时出现 "err:seh:setup_exception stack overflow"

c++ - 比较C中的两个int数组

c++ - MongoDB 从 C++ 调用 stats()

c++ - 为什么编译时间的持续时间至关重要?

c++ - 加载/存储宽松原子变量和普通变量有什么区别?