1、问题概述
在使用gcc编译c++代码时会出现undefined reference to `std::cout',如编译如下代码:
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello world!";
return 0;
}
然而,gcc下编译出现的问题是:
root@LAPTOP-LUU3AAQE:/mnt/d/C_Code/cpp_code# gcc 1.cpp -o main -lm
/tmp/ccTCBs3r.o: In function `main':
1.cpp:(.text+0xe): undefined reference to `std::cout'
1.cpp:(.text+0x13): 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*)'
/tmp/ccTCBs3r.o: In function `__static_initialization_and_destruction_0(int, int)':
1.cpp:(.text+0x43): undefined reference to `std::ios_base::Init::Init()'
1.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
2、解决方法
使用g++编译,g++是专门针对c++文件编译的,如:
root@LAPTOP-LUU3AAQE:/mnt/d/C_Code/cpp_code# g++ 1.cpp -o main
root@LAPTOP-LUU3AAQE:/mnt/d/C_Code/cpp_code# ./main
Hello world!root@LAPTOP-LUU3AAQE:/mnt/d/C_Code/cpp_code#
这样用g++编译就通过了。
总结:在linux系统下编译c++代码(*.cpp文件)使用g++。