Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function in CMake whose name is stored in a variable

Tags:

cmake

Is there a way to call a function in CMake using the name that is stored in a variable (for passing functions to functions, etc)?

Here is what I have tried:

cmake_minimum_required(VERSION 3.0)

function(doThing)
endfunction()

set(FuncVar doThing)

${FuncVar}()

Which fails with this error:

Parse error.  Expected a command name, got unquoted argument with text "${FuncVar}".
-- Configuring incomplete, errors occurred!

I can't see why this shouldn't work, but then again I am new to CMake so what do I know.

Thank you for any help!

like image 702
Russell Greene Avatar asked Dec 21 '15 22:12

Russell Greene


2 Answers

Just a quick update: It seems like CMake added this functionality in the current 3.18 Versions via the cmake_language command, the Syntax:

cmake_language(CALL <command> [<args>...])
cmake_language(EVAL CODE <code>...)

Reference for cmake_language https://cmake.org/cmake/help/v3.18/command/cmake_language.html#command:cmake_language

like image 108
benb Avatar answered Oct 06 '22 02:10

benb


I have solved this with a workaround using files.

Lets say you have:

function(do what)
  ...
endfunction()

You want to call different specializations depending on 'what'. You can then do:

function(do what)
  include("do-${what}.cmake")
  do_dynamic()
endfunction()

And in file do-something.cmake:

function(do_dynamic)
  ...
endfunction()

You can create as many specialization files as you want...

like image 37
Meros Avatar answered Oct 06 '22 02:10

Meros