Reputation: 77
Why does my cpp code fail when I try to build it with gcc or clang but not g++? With gcc or clang I get undefined reference errors, but no errors with g++
This is my simple program:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
➜ clang main.cpp
/bin/x86_64-unknown-linux-gnu-ld: /tmp/main-986467.o: in function main': main.cpp:(.text+0x11): undefined reference to
std::cout'
➜ gcc main.cpp -o myProg
/bin/ld: /tmp/ccJjbZYp.o: warning: relocation against _ZSt4cout' in read-only section
.text' /bin/ld: /tmp/ccJjbZYp.o: in function main': main.cpp:(.text+0xe): undefined reference to
std::cout'
Upvotes: 1
Views: 1503
Reputation: 117148
The code compiles with gcc
and clang
- but since they are usually used to compile C
programs, they do not link with the C++ standard library by default - so the linking phase fails.
You can link with a C++ standard library to confirm this.
Examples:
gcc main.cpp -lstdc++
clang main.cpp -stdlib=libc++ -lc++
Upvotes: 1