[CMake] TRY_COMPILE without linking...

Michael Hertling mhertling at online.de
Tue May 25 20:57:45 EDT 2010


On 05/25/2010 06:13 PM, Theodore Papadopoulo wrote:
> In porting a library (blitz) from autoconf to cmake, I have the 
> sub-project of testing C++ compiler features.
> The autoconf way was to create some C++ files and test that they are 
> compiling (and just compiling not linking).
> 
> TRY_COMPILE (in the variant that creates automatically the CMake 
> project) seems to oblige me to link the code.
> Many of the tests (taken from autoconf) do not include a main(), some 
> the tests fail. Obviously, I can create a main,
> but I wondered if there was an easy way to avoid the linking phase 
> (without having to create my own CMake project
> for all those files).

Use the CMAKE_FLAGS of TRY_COMPILE() to pass in a no-op for the linker:

TRY_COMPILE(...
    CMAKE_FLAGS "-DCMAKE_CXX_LINK_EXECUTABLE='echo not linking now...'"
...)

For an example, look at the following CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(TRY_COMPILE_NO_LINK CXX)
FILE(WRITE A.cxx "void f(void){}")  # compiles
FILE(WRITE B.cxx "void f(void){")   # doesn't
TRY_COMPILE(RES1 ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/A.cxx OUTPUT_VARIABLE LOG1)
MESSAGE("RES1: ${RES1}")
MESSAGE("LOG1: ${LOG1}")
TRY_COMPILE(RES2 ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/A.cxx CMAKE_FLAGS
"-DCMAKE_CXX_LINK_EXECUTABLE='echo not linking now...'" OUTPUT_VARIABLE
LOG2)
MESSAGE("RES2: ${RES2}")
MESSAGE("LOG2: ${LOG2}")
TRY_COMPILE(RES3 ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/B.cxx CMAKE_FLAGS
"-DCMAKE_CXX_LINK_EXECUTABLE='echo not linking now...'" OUTPUT_VARIABLE
LOG3)
MESSAGE("RES3: ${RES3}")
MESSAGE("LOG3: ${LOG3}")

Case 1 fails due to the missing main() in A.cxx, case 3 fails because
B.cxx has a bad syntax, but case 2 does succeed in spite of main()
missing in A.cxx.

Regards,

Michael


More information about the CMake mailing list