'This very simple C++ program using the standard library doesn't compile with GCC
I can't figure out why this isn't working...
I am working in Linux.
g++ doesn't do anything.
gcc prints the following:
/tmp/ccyg7NDd.o: In function `main':
test.cc:(.text+0x14): undefined reference to `std::cout'
test.cc:(.text+0x19): 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*)'
test.cc:(.text+0x21): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
test.cc:(.text+0x29): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
/tmp/ccyg7NDd.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cc:(.text+0x51): undefined reference to `std::ios_base::Init::Init()'
test.cc:(.text+0x56): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccyg7NDd.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
Code:
#include <iostream>
#include <stdio.h>
int main(){
std::cout << "test " << std::endl;
return 0;
};
Solution 1:[1]
gcc is the C compiler. You need to use g++ (or use gcc with option -lstdc++ as pointed out by others). If by nothing is printed after you use g++ is what you mean, you have to execute the compiled binary after you build it (i.e., when g++ completes).
main.cpp:
#include <iostream>
int main(){
std::cout<<"test "<<std::endl;
return 0;
};
Build:
g++ main.cpp -o main
Execute:
./main
Output:
test
Solution 2:[2]
This is C++ code and so you should use executable g++ and not executable gcc.
Also, #include<stdio.h>, is not needed.
Solution 3:[3]
I think you are mistakenly linking with the C compiler command instead of the C++ compiler command. Try this:
g++ test.cc -o test
Solution 4:[4]
I think the underlying issue for this is that the binary name "test" is actually already apart of the Linux system. Typing in "man test" displays a manual for the test binary. I had the exact same issue. It was resolved simply by compiling the binary to something other than "test".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | Peter Mortensen |
| Solution 3 | Thomas Padron-McCarthy |
| Solution 4 | Peter Mortensen |
