0

In cmake how do you do a conditional preprocessor #ifdef #endif.

For example there is a #ifdef #endif below in a soruce file and I want to include this file during compliation?

How would you do that?

#ifdef LWM2M_WITH_LOGS
#include <inttypes.h>
#define LOG(STR) lwm2m_printf("[%s:%d] " STR "\r\n", __func__ , __LINE__)
#endif

The full source file is located here: Source file on github

And the CMakeLists.txt file is located here: CMakeLists.txt

artic sol
  • 349
  • 6
  • 18
  • What do you need? Conditional definition in `CMakeLists.txt` or conditional definition in source file? – Gluttton Oct 23 '17 at 10:00
  • The source file you've linked to is an include file - you include it by having a line like `#include "internals.h"` in your source code. – Chris Turner Oct 23 '17 at 10:00
  • @Gluttton thanks, the conditional definition is already in the source file. Sorry if I wasn't clear but I want this code to be included when I compile so my question is what do I have to put in the CMakeLists file? – artic sol Oct 23 '17 at 10:02
  • 4
    Possible duplicate of [Define preprocessor macro through cmake](https://stackoverflow.com/questions/9017573/define-preprocessor-macro-through-cmake) or [How to define a C++ preprocessor macro through the command line with CMake?](https://stackoverflow.com/questions/8564337/how-to-define-a-c-preprocessor-macro-through-the-command-line-with-cmake) – Florian Oct 23 '17 at 10:22

1 Answers1

3

You can add option in CMakeLists.txt:

option (WITH_LOGS "Use reach logging." OFF)
if (WITH_LOGS)
    # Do some related work (if you need),
    # ...
    # and add definition for compiler 
    target_compile_definitions (lwm2mclient PRIVATE -DLWM2M_WITH_LOGS)
endif ()

And configure your project:

cmake -DWITH_LOGS=ON {path-to-CMakeLists.txt}
Gluttton
  • 5,739
  • 3
  • 31
  • 58