Skip to content

Compiling C++ Programs

With C#, we used dotnet run to compile and execute our programs. With C++, you will have to compile and then run the program as two separate steps.

Illustration of compiling C++ code, and running the resulting program

Example

Have a go at the following.

  1. Create a new folder for your C++ code.

  2. Create a blank “hello.cpp” file for your code.

  3. Open the folder in VS Code

    The following shell commands should achieve this, assuming your code is stored in the ~/Documents/Code path:

    Terminal window
    cd ~/Documents/Code
    mkdir MyCppCode
    cd MyCppCode
    touch hello.cpp
    code .
  4. In VS Code, open the hello.cpp file, and enter the following code:

    #include "splashkit.h"
    int main()
    {
    write_line("Hello World!");
    return 0;
    }
  5. Compile the program using the following shell commands.

    Terminal window
    clang++ hello.cpp -l SplashKit -o hello

    or…

    Terminal window
    g++ hello.cpp -l SplashKit -o hello
  6. Run the program using:

    Terminal window
    ./hello

You should see the message “Hello World!” written to the terminal.

Activities

Do these commands work? How do you run the programs created using the following commands?

  1. clang++ test.cpp -l SplashKit -o test
  2. g++ program.cpp -o my_program
  3. clang++ program.cpp -o my_program
  4. clang++ program.cpp utilities.cpp -o program
Answers
  • 1: Compiles test.cpp into a program called "test". You run using `./test`.
  • 2: This compiles program.cpp into "my_program". This does not link with SplashKit, so this will only work if you do not use any SplashKit code in your project. You run the program using `./my_program`
  • 3: This is the same as 2.
  • 4: This compiles program.cpp and utilities.cpp into a program called "program". You can run this using `./program`.