Question
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?
Solution
Try using 'g++' instead of 'gcc'.
OTHER TIPS
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++
Try:
g++ -o simpletest simpletest.cpp
Try with g++ -o simpletest simpletest.cpp
.
gcc is the C compiler, while g++ is the C++ compiler which also links in the required C++ libraries.
Additionally, you will have to add a return 0;
at the end of your main()
function.
if your compiler is picky you may want to add that all important return 0;
at the end there
You declared your main()
as returning an int
yet you have no return statement. Add return 0;
and see if that helps. If that doesn't solve your problem, try editing your post to include some representative lines from those errors your getting and maybe we can help you better.
g++ was the right answer for me too, I voted it up, thanks.
But my code, a little ditty that I've been using since Feb 13, 1998 (first comment), to calculate effective gross pay and withholding for our kid's nanny, was far TOO simple even for g++. In terms of the example above, my Stroustrup-second-edition-compliant dinosaur went:
// too simple!
#include <iostream.h>
#include <stdlib.h>
main() {
cout << "Hello World!" << endl;
}
This will give you a full terminal window of error messages. Everything except the curly braces is an error! AND its missing a return line. Time was, this would compile and run correctly in commercial C++ development environments...
Kicking it new-school, I'm now using: // just simple enough
#include <iostream>
#include <stdlib.h>
int main(int argc, char* argv[] ) {
std::cout << "Hello World!" << std::endl;
// TODO - this ought to return success, 0
}
The original questioner had the std::cout and used string from
<string>...
"simple" is a relative term...
Bill