Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C++ code not working

Tags:

c++

gcc

g++

This very simple code gives me tons of errors:

#include <iostream>
#include <string>

int main() {
    std::string test = " ";
    std::cout << test;
}

I tried to compile it on linux by typing gcc -o simpletest simpletest.cpp on the console. I can't see why it isn't working. What is happening?

like image 679
liewl Avatar asked Aug 09 '26 12:08

liewl


2 Answers

Try using 'g++' instead of 'gcc'.

like image 94
grieve Avatar answered Aug 11 '26 02:08

grieve


To add to what others have said: g++ is the GNU C++ compiler. gcc is the GNU compiler collection (not the GNU C compiler, as many people assume). gcc serves as a frontend for g++ when compiling C++ sources. gcc can compile C, C++, Objective-C, Fortran, Ada, assembly, and others.

The reason why it fails trying to compile with gcc is that you need to link in the C++ standard library. By default, g++ does this, but gcc does not. To link in the C++ standard library using gcc, use the following:

gcc -o simpletest simpletest.cpp -lstdc++
like image 34
Adam Rosenfield Avatar answered Aug 11 '26 01:08

Adam Rosenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!