Introduction to Handling C++ Code
In our ongoing web service project, we need to work with C++ source code. Our goal is to ensure that this code compiles and runs in a Linux environment using GCC inside a Docker container. We are not using make or focusing on minimizing the environment size for now.
You can find the sample code created for this purpose here.
Searching for a Docker Image
Searching for GCC on Docker Hub revealed an official image available here.
We'll use this image (although there might be a lighter one available).
Creating the C++ Source Code
Let's create a simple Hello World! program in C++.
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
}
Creating a Script for Compiling and Executing
Here's a script to compile the C++ file. Place it in the same directory as your .cpp file.
#!/bin/bash
# Compile
g++ hello.cpp -o hello
# Execute
./hello
Creating docker-compose.yml
After pulling the official Docker image, we'll use it to execute build.sh.
version: '3'
services:
gcc-cpp-sample:
image: 'gcc:9.2'
volumes:
- ./cpp:/src/cpp
working_dir: /src/cpp
command: ./build.sh
Ensure the cpp folder is at the same level as docker-compose.yml, and place hello.cpp and build.sh inside it.
Execution!
By executing the command:
docker-compose up
the message Hello World! was successfully displayed!
Sample Code
You can find the sample code here. In addition to what's covered in this article, it also includes compiling and executing C language programs.
Conclusion
Returning to GCC after about 10 years was a great mental exercise.
This article was created with reference to the following resources. Thank you for the clear and informative articles.
Additionally, if you're concerned about the size of the official Docker image, you may want to consider Alpine Linux for a lighter environment. Here's a comprehensive guide:
Top comments (0)