[c++] How to compile and run C/C++ in a Unix console/Mac terminal?

How can I compile/run C or C++ in Unix console or a Mac terminal?

(I know it, forget it, and relearn it again. Time to write it down.)

This question is related to c++ c macos console terminal

The answer is


Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.


gcc main.cpp -o main.out  
./main.out

To compile C or C++ programs, there is a common command:

  1. make filename

  2. ./filename

make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs & g++ for c++

For C:

gcc filename.c

./a.out

For C++:

g++ filename.cpp

./a.out

Two steps for me:

first:

make foo

then:

./foo

Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.


Two steps for me:

first:

make foo

then:

./foo

A compact way to go about doing that could be:

make foo && ./$_

Nice to have a one-liner so you can just re-run your executable again easily.


This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.

$ g++ -o lab21 iterative.cpp

-o is the letter O not zero

lab21 will be your executable file

iterative.cpp is your c++ file

After you run that command type the following in terminal to run your program:

$ ./lab21

Running a .C file using the terminal is a two-step process. The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:

username$ gcc /Desktop/test.c 

In the second step, run the following command:

username$ ~/a.out

In order to compile and run a cpp source code from Mac terminal one needs to do the following:

  1. If the path of cpp file is somePath/fileName.cpp, first go the directory with path somePath
  2. To compile fileName.cpp, type c++ fileName.cpp -o fileName
  3. To run the program, type ./fileName

A compact way to go about doing that could be:

make foo && ./$_

Nice to have a one-liner so you can just re-run your executable again easily.


For running c++ files run below command, Assuming file name is "main.cpp"

1.Compile to make object file from c++ file.

g++ -c main.cpp -o main.o

2.Since #include <conio.h> does not support in MacOS so we should use its alternative which supports in Mac that is #include <curses.h>. Now object file needs to be converted to executable file. To use curses.h we have to use library -lcurses.

g++ -o main main.o -lcurses

3.Now run the executable.

./main

Assuming the current directory is not in the path, the syntax is ./[name of the program].

For example ./a.out


gcc main.cpp -o main.out  
./main.out

You need to go into the folder where you have saved your file. To compile the code: gcc fileName You can also use the g++ fileName This will compile your code and create a binary. Now look for the binary in the same folder and run it.


I found this link with directions:

http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/

Basically you do:

gcc hello.c
./a.out (or with the output file of the first command)

just enter in the directory in which your c/cpp file is.

for compiling and running c code.

$gcc filename.c
$./a.out filename.c

for compiling and running c++ code.

$g++ filename.cpp
$./a.out filename.cpp

"$" is default mac terminal symbol


Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.


gcc main.cpp -o main.out  
./main.out

Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.


Ryan, I am changing this to be an answer instead of a comment, since it appears I was too brief. Do all of this in "Terminal".

To use the G++ compiler, you need to do this:

  1. Navigate to the directory in which you stored the *.cpp file.

    cd ~/programs/myprograms/
    (the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)

  2. Compile it

    g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. bin is just common on unix.)

    There should be NOTHING returned if it was successful, and that is okay. Generally you get returns on failures.

    However, if you type ls, you will see the list of files in the same directory. For example you would see the other folders, input.cpp and output.bin

  3. From inside the directory, now execute it with ./outbut.bin


To compile C or C++ programs, there is a common command:

  1. make filename

  2. ./filename

make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs & g++ for c++

For C:

gcc filename.c

./a.out

For C++:

g++ filename.cpp

./a.out

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

gcc main.cpp -o main.out  
./main.out

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

In order to compile and run a cpp source code from Mac terminal one needs to do the following:

  1. If the path of cpp file is somePath/fileName.cpp, first go the directory with path somePath
  2. To compile fileName.cpp, type c++ fileName.cpp -o fileName
  3. To run the program, type ./fileName

Ryan, I am changing this to be an answer instead of a comment, since it appears I was too brief. Do all of this in "Terminal".

To use the G++ compiler, you need to do this:

  1. Navigate to the directory in which you stored the *.cpp file.

    cd ~/programs/myprograms/
    (the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)

  2. Compile it

    g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. bin is just common on unix.)

    There should be NOTHING returned if it was successful, and that is okay. Generally you get returns on failures.

    However, if you type ls, you will see the list of files in the same directory. For example you would see the other folders, input.cpp and output.bin

  3. From inside the directory, now execute it with ./outbut.bin


just enter in the directory in which your c/cpp file is.

for compiling and running c code.

$gcc filename.c
$./a.out filename.c

for compiling and running c++ code.

$g++ filename.cpp
$./a.out filename.cpp

"$" is default mac terminal symbol


All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.

$ g++ -o lab21 iterative.cpp

-o is the letter O not zero

lab21 will be your executable file

iterative.cpp is your c++ file

After you run that command type the following in terminal to run your program:

$ ./lab21

Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

Running a .C file using the terminal is a two-step process. The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:

username$ gcc /Desktop/test.c 

In the second step, run the following command:

username$ ~/a.out

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

You need to go into the folder where you have saved your file. To compile the code: gcc fileName You can also use the g++ fileName This will compile your code and create a binary. Now look for the binary in the same folder and run it.


Assuming the current directory is not in the path, the syntax is ./[name of the program].

For example ./a.out


Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

Assuming the current directory is not in the path, the syntax is ./[name of the program].

For example ./a.out


I found this link with directions:

http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/

Basically you do:

gcc hello.c
./a.out (or with the output file of the first command)

For running c++ files run below command, Assuming file name is "main.cpp"

1.Compile to make object file from c++ file.

g++ -c main.cpp -o main.o

2.Since #include <conio.h> does not support in MacOS so we should use its alternative which supports in Mac that is #include <curses.h>. Now object file needs to be converted to executable file. To use curses.h we have to use library -lcurses.

g++ -o main main.o -lcurses

3.Now run the executable.

./main

Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to macos

Problems with installation of Google App Engine SDK for php in OS X dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac Could not install packages due to an EnvironmentError: [Errno 13] How do I install Java on Mac OSX allowing version switching? Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) How can I install a previous version of Python 3 in macOS using homebrew? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working

Examples related to terminal

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave Flutter command not found VSCode Change Default Terminal How to switch Python versions in Terminal? How to open the terminal in Atom? Color theme for VS Code integrated terminal How to edit a text file in my terminal How to open google chrome from terminal? Switch between python 2.7 and python 3.5 on Mac OS X