对“std::cout"的未定义引用

时间:2023-04-11
本文介绍了对“std::cout"的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

以这个为例:

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

它抛出错误:

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.
";
}

抛出错误:

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 Wheezy.

Note: I am using Debian 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++ 默认链接标准库.

as cout is present in the C++ standard library, which would need explicit linking with -lstdc++ when using gcc; g++ links the standard library by default.

使用gcc,(g++ 应该优于gcc)

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

这篇关于对“std::cout"的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:将非 constexpr 标准库函数视为 constexpr 是否符合编译器扩展? 下一篇:在 C 代码中使用 C++ 库

相关文章