Search code examples
dockercmakemakefiledockerfile

cmake and make with -j flag produces error in docker


In my dockerfile, I have this:

RUN cmake -j$(nproc) -S . -B build

When I run it, it produces this error: CMake Error: Unknown argument -j16

I have cmake > 3.12. What is the issue here? It runs perfectly when I do it outside of the docker in the host machine.


Solution

  • If you want to use the -j option with cmake then try something like this:

    🗎 Dockerfile

    FROM ubuntu:latest
    
    RUN apt-get update -qq && apt-get install -y -qq cmake g++
    
    COPY . .
    
    RUN cmake -S . -B build
    RUN cmake --build build -j$(nproc)
    

    Loosely speaking, the first time cmake is run it generates the build directory and writes a suitable Makefile. The second time cmake is run with the --build argument it actually does the build. It effectively uses the make command and that accepts the -j argument, specifying the number of concurrent processes. Obviously for the example code below this is overkill but will make a difference for a large project.

    Files required to complete the example:

    🗎 CMakeLists.txt

    cmake_minimum_required(VERSION 3.10)
    project(project)
    
    add_executable(executable main.cpp)
    
    install(TARGETS executable DESTINATION bin)
    

    🗎 main.cpp

    #include <iostream>
    
    int main() {
        std::cout << "Hello, CMake world!" << std::endl;
        return 0;
    }
    

    Logs for relevant part of build process:

    Step 4/5 : RUN cmake -S . -B build
     ---> Running in 1fceddb78831
    -- The C compiler identification is GNU 11.4.0
    -- The CXX compiler identification is GNU 11.4.0
    -- Detecting C compiler ABI info
    -- Detecting C compiler ABI info - done
    -- Check for working C compiler: /usr/bin/cc - skipped
    -- Detecting C compile features
    -- Detecting C compile features - done
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Check for working CXX compiler: /usr/bin/c++ - skipped
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /build
    Removing intermediate container 1fceddb78831
     ---> 73e99ae72e90
    Step 5/5 : RUN cmake --build build -j$(nproc)
     ---> Running in ac07d5ad7e0e
    [ 50%] Building CXX object CMakeFiles/executable.dir/main.cpp.o
    [100%] Linking CXX executable executable
    [100%] Built target executable
    Removing intermediate container ac07d5ad7e0e
     ---> e196a5849f75
    

    Check executable.

    enter image description here