0

If I build a cmake file, create an executeble with make and delete everything except the executable, the executable is still functional. Can I,

  1. build the file but the only output is the file that can be executed with ./project

or

  1. have all of the files build, create the executable with make, then delete everything except the executable afterwards

and if so, how do I?

2 Answers2

2

If I am getting this correctly, you want to create a stand-alone binary that cannot be executed even if the docker image does not has any dependencies then you need to use static option during the build - i am not expert in this - maybe as described in the following answer of Compiling a static executable with CMake.

Next you might use a multi-stage builds in docker which will makes you able to have a final minimal image with your executable file only without any build dependencies, just the needed packages for your run-time environment. I have an example not with make, it was created using g++ but achieving the similar concept as below:

FROM gcc:5 as builder
COPY ./hello_world_example.cc /hello_world_example.cc
RUN g++ -o hello_world_binary -static hello_world_example.cc && chmod +x hello_world_binary

FROM debian:jessie
COPY --from=builder /hello_world_binary /hello_world_binary
CMD ["/hello_world_binary"]

And the final result when you run the container:

$ docker run --rm -it helloworldimage:latest
Hello from Dockerized image 
Mostafa Hussein
  • 11,063
  • 3
  • 36
  • 61
  • Using scratch image could be an issue due to lack of system binaries if application is more complex than hello world. Better to use some system image like ubuntu or debian – Miq Mar 17 '19 at 08:58
  • @Miq, thanks! I have updated the answer, any other recommendations regarding the cmake part ? – Mostafa Hussein Mar 17 '19 at 09:00
  • Nope, I would also use multistage build. As for cmake I'm not an expert, but as I remember it wasn't so hard to build package with it. – Miq Mar 17 '19 at 09:09
0

Why do you need that?

You can add install() command to your CMakeLists.txt and then call make install to copy your executable into CMAKE_INSTALL_PREFIX directory. If you set CMAKE_INSTALL_PREFIX to an empty dir, you'd end with a directory containing only your executable file.

arrowd
  • 33,231
  • 8
  • 79
  • 110