g++ compile error

不羁岁月 提交于 2020-01-02 02:01:39

问题


I'm a newbie in Ubuntu. I tried to compile a simple "Hello World!" c++ code in Ubuntu 11.04, with that code (in terminal):

gcc -Wall -W -Werror tex.cpp -o tex. 

but compiler returned a lot of errors :

/tmp/ccL8c1p8.o: In function `main':
tex.cpp:(.text+0xa): undefined reference to `std::cout'
tex.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*)'
/tmp/ccL8c1p8.o: In function `__static_initialization_and_destruction_0(int, int)':
tex.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
tex.cpp:(.text+0x42): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status
mohrd@mio:~$ gcc -Wall -W -Werror tex.cpp -o tex.
/tmp/ccEke5JP.o: In function `main':
tex.cpp:(.text+0xa): undefined reference to `std::cout'
tex.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*)'
/tmp/ccEke5JP.o: In function `__static_initialization_and_destruction_0(int, int)':
tex.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
tex.cpp:(.text+0x42): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status

simple code :

#include <algorithm>
#include <iostream>
using namespace std;

int main ()
{
  std::cout << "Hello World!";
  return 0;
}

Why? and what should I do???

many thanks ...


回答1:


You need to use the g++ (or c++) command to compile your program, using "gcc" will compile it as c++ due to the .cpp extension but not link in the required c++ libraries.




回答2:


Use g++ instead of gcc for compiling C++ code:

g++ -Wall -W -Werror tex.cpp -o tex

gcc does not link stdc++ library by default which is required for your code.




回答3:


Use the g++ command instead of gcc.




回答4:


Try:

g++ -Wall hello.cpp -o hello

Beacuse you are trying to compile C++ code, not C code!

-Wall means Warning ALL, so you'll already see all the warnings

Also, name your programs and source files meaningfully!

LE: of course -Werror remains your choice

LE2: no need of #include <algorithm> in your code, so you can remove it!



来源:https://stackoverflow.com/questions/6847105/g-compile-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!