错误"undefined reference to 'std::cout'"

Error "undefined reference to 'std::cout'"

本文关键字:cout std undefined 错误 reference to      更新时间:2023-10-16
这是

一个例子:

#include <iostream>
using namespace std;
int main()
{
    cout << "Hola, moondo.n";
}

它抛出错误:

gcc -c main.cpp gcc -o edit main.o  main.o: In function `main':
main.cpp:(.text+0xa): undefined reference to `std::cout'
main.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*)'
main.o: In function `__static_initialization_and_destruction_0(int,int)':
main.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
main.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld
returned 1 exit status make: *** [qs] Error 1

另外,此示例:

#include <iostream>
int main()
{
    std::cout << "Hola, moondo.n";
}

抛出错误:

gcc -c main.cpp gcc -o edit main.o  main.o: In function `main':
main.cpp:(.text+0xa): undefined reference to `std::cout'
main.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*)'
main.o: In function `__static_initialization_and_destruction_0(int,int)': main.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
main.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld
returned 1 exit status make: *** [qs] Error 1

注意:我正在使用 Debian 7 (Wheezy)。

编译程序:

g++ -Wall -Wextra -Werror -c main.cpp -o main.o
     ^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.

由于cout存在于C++标准库中,因此在使用gcc时需要与-lstdc++显式链接; 默认情况下,g++链接标准库。

对于gcc,(g++应该优先于gcc

gcc main.cpp -lstdc++ -o main.o

是的,使用g++命令对我有用:

g++ my_source_code.cpp

假设code.cpp是源代码,以下内容不会抛出错误:

make code
./code

在这里,第一个命令编译代码并创建具有相同名称的可执行文件,第二个命令运行它。在这种情况下,无需指定g++关键字。

生成文件

如果您正在使用 makefile 并且您最终像我一样来到这里,那么这可能是您正在寻找的内容,或者:

如果您使用的是生成文件,则需要更改cc

如下所示
my_executable : main.o
    cc -o my_executable main.o

CC = g++
my_executable : main.o
    $(CC) -o my_executable main.o

在 CMake 中添加以下行会使 gcc 与 std 链接,从而识别 std::cout

target_link_libraries(your_project
        PRIVATE
        -lstdc++
        )

FWIW,如果你想要一个makefile,这里有一个你可以通过切换顶部的编译器来做任何一个答案。

# links stdc++ library by default
# CC := g++
# or
CC := cc
all: hello
util.o: util.cc
        $(CC) -c -o util.o  util.cc
main.o: main.cc
        $(CC) -c -o main.o  main.cc
# notice -lstd++ is after the .o files
hello: main.o util.o
        $(CC) -o hello main.o util.o -lstdc++
clean:
        -rm util.o main.o hello