How can I use Docker to build a C++ application?
For context, I am working on a Linux server which has an older version of gcc
/g++
installed. (Version 12.)
This version does not support the latest C++ 23 features.
However, Version 14 does have support for some C++ 23 features.
I do not want to install Version 14 directly onto the server and replace the default Version 12 compiler. The reason is that this is one possible way to break the system, as there may be incompatiable changes between major versions of g++
/gcc
compiler releases.
The rest of the Operating System depends on having a compatiable compiler, therefore swapping one for the other is not advisable.
For example, how would I build this example C++ 23 application?
#include <print>
int main() {
std::println("hello world");
return 0;
}
Please note that if an application is compiled inside a Docker container with a different compiler version to the default installed compiler version, then this application should also be run inside a Docker container with the same version of the standard library.
Note: This seems to have caused quite a debate in the comments. While it may be possible to run an application built inside a Docker Container on the host system, it is not generally advisable to do so, and this cannot be guaranteed to work. If you create an environment to build an application then you should also run it in an equivalent environment.
This is because, as mentioned in the question, there may be incompatiable changes between compiler versions.
The following example Dockerfile
demonstrates one possible approach for how to construct a container image which can be used to build a C++ 23 application.
It can of course be modified for different C++ versions.
FROM ubuntu:24.04 AS build
RUN apt update
RUN apt install software-properties-common -y
RUN apt-add-repository ppa:ubuntu-toolchain-r/ppa
RUN apt update
RUN apt install build-essential -y
RUN apt install gcc-14 -y
RUN apt install g++-14 -y
RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-14 14
RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-14 14
RUN apt install cmake -y
WORKDIR /workspace/my-project-name
COPY my-project-dir my-project-dir
RUN cd my-project-dir && cmake .
RUN cd my-project-dir && mkdir -p build
RUN cd my-project-dir && cmake --build build
FROM ubuntu:24.04
COPY --from=build /workspace/my-project-name/my-project-dir/build/a.out /usr/local/bin/a.out
CMD ["a.out"]
Of course, recommend you change a.out
and the other directory names to something sensible.
I have assumed that you have a suitable CMakeLists.txt
.
If you are using an alternative build system to cmake
, then you will need to install the relevant build tools, and add the relevant build files.
As a trivial example, if you are calling g++
directly from a script, you could just copy the build script and run it inside the container.