[CMake] Exclude source files from build for a specific configuration with Visual Studio

Michael Hertling mhertling at online.de
Sun Apr 3 07:19:57 EDT 2011


On 04/01/2011 03:02 PM, Gaylord Charles wrote:
> Hello,
> 
> I am migrating a project from Visual Studio 8 to CMake and I look for a way
> to exclude files from build for a defined configuration.
> 
> I think the "HEADER_FILE_ONLY" source file property can suit my needs and it
> would be great to have a "HEADER_FILE_ONLY_<CONFIG> version.
> 
> But maybe there is a "workaround" that enables to get this kind of behavior.
> 
> Thanks,
> Gaylord CHARLES

AFAIK, you can not prevent the concerned files from being compiled, but
you can prevent their object files from being incorporated in the final
binaries. Admittedly, the method I could offer is somewhat weird:

First of all, isolate the concerned files in a static library; linking
against such a one is quite the same as incorporating the object files
immediately. If desired, a shared library is alright, too. Further on,
you need an intermediate empty static library as an imported target
since imported targets can have arbitrary *configuration-specific*
dependencies. Look at the following CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(CONFIGEXCLUDE C)
FILE(WRITE ${CMAKE_BINARY_DIR}/f.c "void f(void){}\n")
ADD_LIBRARY(f STATIC f.c)
ADD_LIBRARY(helper STATIC "")
SET_TARGET_PROPERTIES(helper PROPERTIES LINKER_LANGUAGE "C")
EXPORT(TARGETS helper NAMESPACE "reimp_"
    FILE ${CMAKE_BINARY_DIR}/helper.cmake)
INCLUDE(${CMAKE_BINARY_DIR}/helper.cmake)
SET_TARGET_PROPERTIES(reimp_helper PROPERTIES
    IMPORTED_LINK_INTERFACE_LIBRARIES "f"
    IMPORTED_LINK_INTERFACE_LIBRARIES_CUSTOM "")
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c "int main(void){return 0;}\n")
ADD_EXECUTABLE(main main.c)
TARGET_LINK_LIBRARIES(main reimp_helper)
ADD_DEPENDENCIES(main f helper)

Target "f" comprises the files to exclude for a specific configuration.
Target "helper" is the intermediate empty static library; it gets re-
imported to the project to set its IMPORTED_LINK_INTERFACE_LIBRARIES
property - to "f" generically and to "" for the "CUSTOM" configuration.
Finally, target "main" is linked against the re-imported helper target.
On *nix, I can see "main" being linked against libf.a unless the build
type in CMAKE_BUILD_TYPE is set to "custom", and I suppose it'll work
in Visual Studio, too. Note that you need to establish the dependency
of main on f and the helper explicitly by ADD_DEPENDENCIES() because
TARGET_LINK_LIBARIES() can't do this anymore.

'hope that helps.

Regards,

Michael


More information about the CMake mailing list