Compile and Execute C++ in One Step

Working like golang

In Golang, we can use go run main.go to compile and execute the source file in one step. In C++, by default, we need to compile first and then execute.

We can create a shell script to make C++ work like Golang.

Step 1.
Create a script in a bin directory, named cpprun. For example, /usr/local/bin or ~/bin.

Step 2.
Add the following contents to cpprun.

#!/bin/bash
g++ -std=c++11 -o /tmp/a.out "$@" && /tmp/a.out

Step 3.
Make the script executable.

chmod +x cpprun

Step 4.
Run the C++ file.

cpprun main.cpp

Explanation

  • The script uses g++ to compile the provided C++ file(s) with C++11 standard to a temporary executable /tmp/a.out.
  • If compilation succeeds (&&), it runs the executable.
  • Using /tmp/a.out avoids cluttering the current directory with temporary files.
  • The "$@" allows passing multiple files or additional arguments to g++.

Important Notes

  • Ensure g++ is installed: sudo apt install g++ (on Ubuntu/Debian).
  • The script assumes the file has a main function.
  • For projects with multiple files or dependencies, consider using Makefiles or build systems like CMake.
  • If you need to pass runtime arguments to the program, modify the script to handle them separately.
  • Security: Running executables from /tmp is fine for personal use, but be cautious with untrusted code.

Example

Create main.cpp:

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Run:

cpprun main.cpp
# Output: Hello, World!

References