Compiling simple Hello World program on OS X via command line

C++XcodeMacos

C++ Problem Overview


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 ?

C++ Solutions


Solution 1 - C++

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;
}

Solution 2 - C++

g++ hw.cpp -o hw
./hw

Solution 3 - C++

user@host> g++ hw.cpp
user@host> ./a.out

Solution 4 - C++

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

Solution 5 - C++

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).

Solution 6 - C++

The new version of this should read like so:

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

Solution 7 - C++

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.

Solution 8 - C++

Use the following for multiple .cpp files

g++ *.cpp
./a.out

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionerikvoldView Question on Stackoverflow
Solution 1 - C++Martin YorkView Answer on Stackoverflow
Solution 2 - C++nobodyView Answer on Stackoverflow
Solution 3 - C++Sam MillerView Answer on Stackoverflow
Solution 4 - C++Ignacio Vazquez-AbramsView Answer on Stackoverflow
Solution 5 - C++José RojasView Answer on Stackoverflow
Solution 6 - C++BadmanchildView Answer on Stackoverflow
Solution 7 - C++Stephen CanonView Answer on Stackoverflow
Solution 8 - C++wLcView Answer on Stackoverflow