Compiling a simple Hello World program on OS X via the command line

I have a simple greeting example that I am trying to compile on OS X with the name hw.cpp :

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

I would like to compile it with gcc , but I was not successful. I would also like to hear other options, e.g. using Xcode?

+53
c ++ xcode macos
Nov 01 '10 at 21:39
source share
6 answers

Try

 g++ hw.cpp ./a.out 

g++ is the C ++ compiler interface for GCC.
gcc is the C compiler interface to GCC.

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

Although I prefer a slightly more detailed approach:

 #include <iostream> int main() { std::cout << "Hello world!" << std::endl; } 
+112
Nov 01 '10 at 21:42
source share
 g++ hw.cpp -o hw ./hw 
+21
Nov 01 '10 at 21:41
source share
 user@host> g++ hw.cpp user@host> ./a.out 
+5
Nov 01. '10 at 21:41
source share

Compiling with gcc requires passing a few command line parameters. Compile it with g++ .

+4
Nov 01 '10 at 21:43
source share

You did not indicate what error you are seeing.

Is the problem that gcc gives you an error message or that you cannot start gcc at all?

If this is the last, the most likely explanation is that you did not check "Support for UNIX support" when installing development tools, so the command line executables are not installed in your path. Reinstall the development tools and be sure to click "configure" and check the box.

+1
Nov 01. '10 at 21:46
source share

The new version should look like this:

 xcrun g++ hw.cpp ./a.out 
+1
Jan 03 '13 at 23:07
source share



All Articles