Skip to content

Instantly share code, notes, and snippets.

@raytroop
Last active September 29, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raytroop/8d48e5f5a1a49cd712f85b0af069efba to your computer and use it in GitHub Desktop.
Save raytroop/8d48e5f5a1a49cd712f85b0af069efba to your computer and use it in GitHub Desktop.
Conditional compilation
this page intentionally left blank

CMakeLists.txt add_definitions

cmake_minimum_required(VERSION 3.2)

option(DEBUG "Option description" OFF)

if(DEBUG)
    add_definitions(-DDEBUG)
endif(DEBUG)

add_executable(cond conditional.cpp)

without debug

$ cmake ..
$ make
$ ./cond

WITH debug

$ cmake -DDEBUG=ON ..
$ make
$ ./cond
a[0] = 2
a[1] = 3
a[2] = 4
a[3] = 5

conditional.cpp

#include <iostream>

#define na 4

int main() {
  int a[na];

  a[0] = 2;
  for (int n = 1; n < na; n++) a[n] = a[n-1] + 1;

#ifdef DEBUG
  // Only kept by preprocessor if DEBUG defined
  for (int n = 0; n < na; n++) {
    std::cout << "a[" << n << "] = " << a[n] << std::endl;
  }
#endif 
  
  return 0;
}

-DDEBUG args

$ g++ -Wall -Wextra -Wconversion conditional.cpp -o conditional
$ ./conditional
$ g++ -Wall -Wextra -Wconversion conditional.cpp -o conditional -DDEBUG
$ ./conditional
a[0] = 2
a[1] = 3
a[2] = 4
a[3] = 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment