[Cmake] use of cmake options in source code

Andy Cedilnik andy . cedilnik at kitware . com
28 Aug 2003 07:49:27 -0400


Hi Mónica,

This is all described in section 6.4 of MAstering CMake.

Two options:

Easy, but not so good option:

IF(CLEAR_HAS_VTK)
  ADD_DEFINITION(-DHAS_VTK)
IF(CLEAR_HAS_VTK)

Better option:

Create file ClearConfig.h.in and put in something like:

#cmakedefine CLEARR_HAS_VTK

Then in your CMakeLists.txt after OPTION(CLEAR_HAS_VTK...)

IF(CLEAR_HAS_VTK)
  CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/ClearConfig.h.in
    ${CMAKE_CURRENT_BINARY_DIR}/ClearConfig.h)
ENDIF(CLEAR_HAS_VTK)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})

Now in your source code you include ClearConfig.h:

#include "ClearConfig.h"

#ifdef CLEAR_HAS_VTK
....
...
#endif

Ok, you will say, why use the second option if the first one is so
simple? Well, some day your coworker will want to use Clear in his
project. He will however only have precompiled libraries and header
files. He has no idea that he has to use CLEAR_HAS_VTK. But if you
configure one of the header files, then it does not matter, because the
header files contain all the flags.

			Andy
	
On Thu, 2003-08-28 at 04:39, Mónica Hernández Giménez wrote:
> Hi all!
> 
> I defined a flag in my CMakeLists.txt file to compile my library with or 
> without VTK:
> 
> OPTION(HAS_VTK "build with VTK" ON)
> MARK_AS_ADVANCED(CLEAR HAS_VTK)
> 
> Now i would like to use this HAS_VTK in my source code this way:
> 
> int main(int argc, char **argv)
> {
> 
> #ifdef HAS_VTK
> 
> cout<<"I can use VTK libraries"<<endl;
> 
> #else
> 
> cout<<"I can't use VTK libraries"<<endl;
> 
> #endif
> 
> }
> 
> Now the option HAS_VTK is set to ON in my CMakeLists.txt but the result of 
> this program is cout<<"I can't use VTK libraries"<<endl;
> 
> How can the source code know that the option HAS_VTK is defined?