batch-filecmakeprebuild

call batch file from CMakeLists.txt


My company uses different Visual Studio for different projects. VS2003,VS2008,VS2010,VS2013... So I have different VS install on my machine. I'm using cmake to manage my projects, and I use a hotkey F5 to build the project, the F5 is simply call nmake from the build directory.

The problem is I need to call different vcvarsall.bat to setup the build environment first, otherwise cmake use the values from environment variable, which causes build error.

How can I call batch files from CMakeLists.txt?


Solution

  • You seem to be approaching this from the wrong angle. When CMakeLists are being processed, the environment is that in which CMake was launched (and for the NMake generator, it must be correctly configured before CMake starts). Once the buildsystem is generated, it's out of scope for CMake to do anything. Nothing in the CMakeList can set up environment for the build—builds only happen long after CMake has finished running.

    What you could do is add a step to your CMake process which would print out some environment configuration into the build directory; you would then re-bind the hotkey to use that configuration. Something like this:

    if(CMAKE_SIZEOF_VOID_P GREATER 4)
      set(Arg amd64)
    else()
      set(Arg x84)
    endf()
    
    file(
      WRITE ${CMAKE_BINARY_DIR}/build.bat
      "@call $ENV{VCINSTALLDIR}\\vsvarsall.bat ${Arg}\n@nmake"
    )
    

    The above is not a copy-and-paste example, it's supposed to convey the general idea.

    VCINSTALLDIR is an environment variable set up by vsvarsall.bat; it's used in the CMake code to get the location of that setup file.