例子如下:

#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

makefile

如果你正在使用makefile文件,并且你像我一样在这里结束,那么这可能是你正在寻找的或:

如果您正在使用makefile,那么您需要更改cc,如下所示

my_executable : main.o
    cc -o my_executable main.o

to

CC = g++

my_executable : main.o
    $(CC) -o my_executable main.o

假设code.cpp是源代码,下面的代码不会抛出错误:

make code
./code

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

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

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

target_link_libraries(your_project
        PRIVATE
        -lstdc++
        )