问题
Shall this be the example:
#include <iostream>
using namespace std;
int main()
{
cout << \"Hola, moondo.\\n\";
}
It throws the error:
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
Also, this example:
#include <iostream>
int main()
{
std::cout<<\"Hola, moondo.\\n\";
}
throws the error:
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
Note: I am using Debian Wheezy.
回答1:
Compile the program with:
g++ -Wall -Wextra -Werror -c main.cpp -o main.o
^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.
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.
With gcc
, (g++
should be preferred over gcc
)
gcc main.cpp -lstdc++ -o main.o
回答2:
Yes, using g++
command worked for me:
g++ my_source_code.cpp
回答3:
Makefiles
If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:
If you're using a makefile, then you need to change cc
as shown below
my_executable : main.o
cc -o my_executable main.o
to
CC = g++
my_executable : main.o
$(CC) -o my_executable main.o
来源:https://stackoverflow.com/questions/28236870/undefined-reference-to-stdcout