Mich
Mich

Reputation: 3594

How to configure CMakeLists to use Windows command line compiler instead of Visual Studio

I would like to convert my project from a Visual Studio solution to build with CMake and compile it with Makefiles.

This is a 2-part question.

  1. Right now the CMakeLists.txt is:

    cmake_minimum_required(VERSION 3.13.0)
    
    project(Project2015 CXX)
    
    add_executable(Project Source/main.cpp)
    

When I run cmake .. out of the build directory, it generates *.vcxproj and *.sln files, but there is no Makefile. How can I change the CMakeLists file to generate a Makefile?

  1. What is the command line equivalent compiler to gcc for windows? And how do I set this compiler as the target for CMake and the generated Makefile? Reading about the build tools https://learn.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line?view=vs-2019 Do I need to target the cl.exe compiler? Would this work with CMake and Makefiles? I'm reading online that these command line flags will set the compiler, how can I add these to the CMakeLists.txt to be used automatically?

    DCMAKE_C_COMPILER=cl 
    DCMAKE_C_COMPILER_FORCED=ON 
    DCMAKE_CXX_COMPILER=cl 
    DCMAKE_CXX_COMPILER_FORCED=ON 
    DCMAKE_BUILD_TYPE=Debug 
    DCMAKE_INSTALL_PREFIX=%CFITSIO_DIR% 
    G"NMake Makefiles"
    

Upvotes: 1

Views: 9472

Answers (2)

Kevin
Kevin

Reputation: 18293

As suggested by @vre, you can run everything from the command line, while still using the Visual Studio generator. Just use CMake's command line build tools:

cmake ..
cmake --build . --config Release

This way, you don't have to open Visual Studio at all to build your libraries/executables.

Another option is to use Microsoft's nmake utility, which will generate NMake Makefiles. You can tell CMake to use this generator instead using this:

cmake -G"NMake Makefiles" ..

The full list of CMake generators you can choose from is listed here.

If you don't want to manually set the CMake generator in the command line, you can set it at the top of your CMakeLists.txt file:

set (CMAKE_GENERATOR "NMake Makefiles" CACHE INTERNAL "" FORCE)

It will be used on the second CMake configuration in this case, as the first run will use the system default generator. If you want CMake to use it on the first configuration, you can utilize the Preload.cmake procedure outlined in this answer.

Upvotes: 6

vre
vre

Reputation: 6744

You should use the build tool mode of CMake for builds from the command line.

After configuring your project for a 64bit build using Visual Studio 2019 e.g. with

cmake -S <sourcedir> -B <builddir> -G "Visual Studio 16 2019" -A x64 

you would run

cmake --build <builddir> --target ALL_BUILD --config Release

For further options see here for an almost quiet build from the command line see here.

Upvotes: 1

Related Questions