130

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 ?

1
  • 8
    "No success" doesn't really help anyone diagnose your problem. Commented Nov 1, 2010 at 21:42

8 Answers 8

232

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

15 Comments

@math: return 0 is implicit in main.
@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.
Ahh, okay. I would still use it for clarity.
@mathepic: That's 1 opinion. Personally I find it clearer to not to use it.
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.
|
48
g++ hw.cpp -o hw
./hw

2 Comments

Out of all the other ones, this one worked out just fine for me. Thanks.
Works for me on mac with the default g++ setup. I had to have the -o file parameter passed.
12
user@host> g++ hw.cpp
user@host> ./a.out

Comments

6

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

Comments

4

Use the following for multiple .cpp files

g++ *.cpp
./a.out

Comments

3

The new version of this should read like so:

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

2 Comments

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)
@Rat-a-tat-a-tat sorry I don't remember, was 3 years ago.
3

Also, you can use an IDE like CLion (JetBrains) or a text editor like Atom, with the gpp-compiler plugin, works like a charm (F5 to compile & execute).

Comments

1

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.

Comments

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.