eamoc
eamoc

Reputation: 77

Simple code will not compile with clang or gcc but it will with g++

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

Answers (1)

Ted Lyngmo
Ted Lyngmo

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

Related Questions