[CMake] Overriding CMAKE_<LANG>_FLAGS on a per target basis for Visual Studio project generation

Dan Peterson petrsnd at gmail.com
Fri Apr 20 03:31:58 EDT 2012


I love cmake, but I am still a bit of a novice, so perhaps there is a
better way to approach this problem.  I am building a library using
cmake.  On Windows I need to be able to build two versions: one that
links statically to the CRT (/MT) and one that links dynamically to
the CRT (/MD).  I would like to avoid setting properties on
directories (not sure if it would work anyway) or doing anything that
requires me to split my project into two pieces.

I know there is a general solution to the CRT linkage problem by
setting CMAKE_<LANG>_FLAGS globally (see
http://stackoverflow.com/questions/1618927/cmake-microsoft-visual-studio-and-monolithic-runtimes).
 It works great, but I cannot figure out a way to accomplish the same
thing on a per target basis.

My CMakeLists.txt for this library is similar to the following:


INCLUDE_DIRECTORIES( "${PROJECT_SOURCE_DIR}" )

SET( MYLIB_SRCS
	foo.h
	bar.h
	baz.h
	foo.cpp )

IF( WIN32 )

	ADD_LIBRARY( MylibMD STATIC ${MYLIB_SRCS} )
	ADD_LIBRARY( MylibMT STATIC ${MYLIB_SRCS} )

	# Statically link to Visual C++ CRT
	FOREACH( Flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG
CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL
CMAKE_CXX_FLAGS_RELWITHDEBINFO )
		IF( ${Flag_var} MATCHES "/MD" )
			STRING( REGEX REPLACE "/MD" "/MT" "${Flag_var}MT" "${${Flag_var}}" )
			SET_TARGET_PROPERTIES( MylibMT PROPERTIES "${Flag_var}" "${${Flag_var}MT}" )
			# I also tried this
			# SET_PROPERTY( TARGET MylibMT PROPERTY "${Flag_var}" "${${Flag_var}MT}" )
		ENDIF( ${Flag_var} MATCHES "/MD" )
	ENDFOREACH( Flag_var )

ELSE( WIN32 )

	ADD_LIBRARY( Mylib STATIC ${MYLIB_SRCS} )

ENDIF( WIN32 )


I tried adding this in with COMPILE_FLAGS and other properties.  I
also tried multiple things like the following in place of the for
loop:


SET_TARGET_PROPERTIES( MylibMT
				PROPERTIES
				STATIC_LIBRARY_FLAGS_DEBUG "/MTd"
				STATIC_LIBRARY_FLAGS_RELEASE "/MT"
				STATIC_LIBRARY_FLAGS_MINSIZEREL "/MT"
				STATIC_LIBRARY_FLAGS_RELWITHDEBINFO "/MT" )


I found this thread on the mailing list:
http://www.cmake.org/pipermail/cmake/2010-August/039046.html, but
couldn't make any use of it, unless it would work to remove all CRT
linkage from the CMAKE_<LANG>_FLAGS and then add it back via
COMPILE_FLAGS or something else; but COMPILE_FLAGS doesn't seem to
have a per configuration variant.

Please let me know if it is even possible to accomplish what I am
trying to do.  Thanks.


More information about the CMake mailing list