1

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'

1 Answer 1

1

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++
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, it makes sense now. i figured the file extension, and or the contents of the filew would lead gcc or clang to figure out that it was c++ code they were dealing with, but obviously not....
@eamoc You're welcome, and yes, as you've noticed, a file ending with .cpp will not make gcc or clang add the necessary libaries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.