Join the Stack Overflow Community
Stack Overflow is a community of 6.2 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I've got a simple hello world example that I'm trying to compile on OS X, named hw.cpp:

#include <iostream>
#include <string>
using namespace std;
int main() {
  cout << "Hello world!" << endl;
return 0;
}

I'd like to compile it using gcc, but I've had no success. I'd also like to hear the other options, like using Xcode ?

share|improve this question
3  
"No success" doesn't really help anyone diagnose your problem. – Gaz Davidson Nov 1 '10 at 21:42
up vote 75 down vote accepted

Try

g++ hw.cpp
./a.out

g++ is the C++ compiler frontend to GCC.
gcc is the C compiler frontend to GCC.

Yes, Xcode is definitely an option. It is a GUI IDE that is built on-top of GCC.

Though I prefer a slightly more verbose approach:

#include <iostream>

int main()
{
    std::cout << "Hello world!" << std::endl;
}
share|improve this answer
1  
Don't forget return 0 – alternative Nov 1 '10 at 21:51
6  
@math: return 0 is implicit in main. – fredoverflow Nov 1 '10 at 22:03
2  
@mathepic: and the +1. It is not required in C++. If main reaches the end of the function without hitting a return then it implicitly returns 0. – Loki Astari Nov 1 '10 at 22:43
1  
Ahh, okay. I would still use it for clarity. – alternative Nov 1 '10 at 23:35
1  
Why a.out? In windows I expect to see a.exe. In *nix we don't need extensions. Why use .out over no extension? a is a weird default name too. – P.Brian.Mackey Mar 5 '15 at 3:58
g++ hw.cpp -o hw
./hw
share|improve this answer
user@host> g++ hw.cpp
user@host> ./a.out
share|improve this answer

Compiling it with gcc requires you to pass a number of command line options. Compile it with g++ instead.

share|improve this answer

You didn't specify what the error you're seeing is.

Is the problem that gcc is giving you an error, or that you can't run gcc at all?

If it's the latter, the most likely explanation is that you didn't check "UNIX Development Support" when you installed the development tools, so the command-line executables aren't installed in your path. Re-install the development tools, and make sure to click "customize" and check that box.

share|improve this answer

The new version of this should read like so:

xcrun g++ hw.cpp ./a.out

share|improve this answer
    
This gives me ld: can't link with a main executable file './a.out' for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) – Eddified Jan 31 '14 at 6:32

It seems to me that make is the easiest way.

make hw
./hw
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.