【问题标题】:gcc compile errors when c++ code is sound [duplicate]当c ++代码正确时,gcc编译错误[重复]
【发布时间】:2017-11-20 01:12:56
【问题描述】:

我在这里的最后一个问题显然是 gcc 而不是代码(代码错误已解决,然后我注意到 gcc 的问题)。从那以后,我编写了一个简短的 hello world 程序,我知道它可以很好地测试这个:

#include <iostream>
using namespace std;

int main()
{
cout << "Hello, World!" << endl;
}

但 gcc 仍然会抛出错误。

我将文件命名为“test.cpp”并将其直接存储在我的主文件夹中,然后尝试:

gcc ./test.cpp -o Test

gcc ~/test.cpp -o Test

gcc /home/josh/test.cpp -o Test

所有 3 次,有和没有大写“Test”。

Gcc 给出以下错误:

/tmp/ccre0DEJ.o: In function `main':
test.cpp:(.text+0xa): undefined reference to `std::cout'
test.cpp:(.text+0xf): 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.cpp:(.text+0x14): 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.cpp:(.text+0x1c): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccre0DEJ.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x4a): undefined reference to `std::ios_base::Init::Init()'
test.cpp:(.text+0x59): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

我的问题是:如何修复 Gcc?如果不是,我应该尝试其他编译器吗?

编辑:我已尝试重新安装 gcc,但仍然失败。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里询问什么以及如何询问。请在提问之前多花点精力研究。
  • 编译错误被打印出来,而不是被抛出。

标签: c++ gcc linker-errors undefined-reference


【解决方案1】:

好的。这是重复的(我通常可以在发布之前发现它)。

在这里找到答案:undefined reference to 'std::cout'

我不得不使用

g++ ~/test.cpp -o Test

而不是

gcc ~/test.cpp -o Test 

注意:实际上,最好在编译时包含所有警告和调试信息,即将
-Wall -Wextra -g 添加到您的 g++gcc 命令中。阅读有关Invoking GCC 的更多信息。

【讨论】:

  • 养成编译所有警告和调试信息的习惯,所以g++ -Wall -Wextra -g ~/test.cpp -o Test
  • 我不记得了,但我输入了它以供参考,直到我知道了哈哈。
【解决方案2】:

请尝试运行 g++ 或在命令中添加“cpp flags”,例如 -lstdc++,它将代码与 c++ 的标准库链接。

gcc 可以编译 cpp 代码,但只能使用正确的标志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2014-09-09
    相关资源
    最近更新 更多