23

I'm wondering how I can use bash command in CMakeLists.txt. What I want is to get the number of processor retrieved using :

export variable=`getconf _NPROCESSORS_ONLN`

and set NB_PROCESSOR to variable using something like :

SET (NB_PROCESSOR variable)

So my question is how can I use the getconf command in CMakeLists.txt and how can I use the result (stored in variable) in CMake SET command?

claf
  • 9,043
  • 17
  • 62
  • 79

2 Answers2

21

This seems to do the trick, and saves the "set" too.

execute_process(COMMAND getconf  _NPROCESSORS_ONLN
                OUTPUT_VARIABLE NB_PROCESSOR)
richq
  • 55,548
  • 20
  • 150
  • 144
  • with this, i see the result of the command during "cmake ." but if I have "#cmakedefine NB_PROCESSOR ${NB_PROCESSOR}" to my config.h.in, I'll get "#undef NB_PROCESSOR" instead of "#define NB_PROCESSOR value". Any clue? – claf Mar 18 '09 at 12:27
  • I messed up - it should be OUTPUT_ not RESULT_VARIABLE. The former stores the output from the program, the latter the result ($? in bash-speak) – richq Mar 18 '09 at 12:53
  • already tried and seems not to work, I think the result may be considered as a string and I want a int. Still trying to find a solution :) – claf Mar 18 '09 at 12:56
  • oups, I was wrong about saying I tried using the output_var, it works! thanks! – claf Mar 18 '09 at 12:58
  • It might be important to remove the trailing whitespaces from the output of getconf (simply append `OUTPUT_STRIP_TRAILING_WHITESPACE` in the execute process cmake command). Using `NB_PROCESSOR` in a precompiler definition may be erroneous otherwise. – breiters Mar 09 '23 at 12:38
9

Use the EXEC_PROGRAM command and then use the CACHE option of the SET command to save the output to a variable like GTK_PKG_FLAGS. Then use the SET command to add the value. Something like this:

IF(NOT GTK_PKG_FLAGS)
   EXEC_PROGRAM(pkg-config ARGS --cflags --libs gtkmm
                OUTPUT_VARIABLE GTK_PKG_FLAGS)
   SET(GTK_PKG_FLAGS "${GTK_PKG_FLAGS}" CACHE STRING "GTK Flags")
ENDIF(NOT GTK_PKG_FLAGS)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GTK_PKG_FLAGS}")

Links: http://www.cmake.org/pipermail/cmake/2005-January/006051.html

Jiang Bian
  • 1,933
  • 3
  • 16
  • 14