【问题标题】:Simple code will not compile with clang or gcc but it will with g++简单的代码不能用 clang 或 gcc 编译,但它可以用 g++
【发布时间】:2021-04-26 11:44:13
【问题描述】:

当我尝试使用 gcc 或 clang 而不是 g++ 构建 cpp 代码时,为什么会失败? 使用 gcc 或 clang 我得到未定义的引用错误,但 g++ 没有错误

这是我的简单程序:

#include <iostream>
using namespace std;
int main() {
      cout << "Hello World!" << endl;
      return 0;
} 

➜ clang main.cpp /bin/x86_64-unknown-linux-gnu-ld: /tmp/main-986467.o: 在函数main': main.cpp:(.text+0x11): undefined reference to std::cout'

➜ gcc main.cpp -o myProg /bin/ld: /tmp/ccJjbZYp.o: 警告:针对_ZSt4cout' in read-only section .text' 重定位/bin/ld: /tmp/ccJjbZYp.o: 在函数main': main.cpp:(.text+0xe): undefined reference to std::cout'中

【问题讨论】:

    标签: c++ gcc g++ clang


    【解决方案1】:

    代码编译gccclang - 但由于它们通常用于编译C程序,默认情况下它们不与C++标准库链接 - 所以链接阶段失败。

    您可以链接到 C++ 标准库来确认这一点。

    例子:

    gcc main.cpp -lstdc++
    
    clang main.cpp -stdlib=libc++ -lc++
    

    【讨论】:

    • 感谢您的回答,现在说得通了。我想出了文件扩展名,或者 filew 的内容会导致 gcc 或 clang 弄清楚他们正在处理的是 c++ 代码,但显然不是....
    • @eamoc 不客气,是的,正如您所注意到的,以.cpp 结尾的文件不会使gccclang 添加必要的库。
    猜你喜欢
    • 2015-02-08
    • 2020-06-03
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多