Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMAKE: Creating and building a list within a function -- with directory, or global scope

I am not entirely familiar with the scoping rules of cmake. I need to buildup a list of various files whilst doing RPC code-generation for an IDL.

function(generate_rpc file_name)
  set(PROTO_FILES ${PROTO_FILES} ${file_name})
endfunction(generate_rpc)

generate_rpc(BasicProtocol.proto)
generate_rpc(dummy.proto)

message(STATUS "PROTO FILES: ${PROTO_FILES}")

The list is empty each time. I need append-able list that can be built from within a function.

like image 297
Hassan Syed Avatar asked Jul 13 '11 12:07

Hassan Syed


People also ask

How do I create a list in CMake?

A list in cmake is a ; separated group of strings. To create a list the set command can be used. For example, set(var a b c d e) creates a list with a;b;c;d;e , and set(var "a b c d e") creates a string or a list with one item in it.

What is parent scope in CMake?

If the PARENT_SCOPE option is given the variable will be set in the scope above the current scope. Each new directory or function creates a new scope. This command will set the value of a variable into the parent directory or calling function (whichever is applicable to the case at hand).

What is ${} in CMake?

Local Variables You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.

What is the function of CMake?

CMakeParseArguments. CMake has a predefined command to parse function and macro arguments. This command is for use in macros or functions. It processes the arguments given to that macro or function, and defines a set of variables which hold the values of the respective options.


2 Answers

Although Macros are defined and called in the same manner as functions, there are some differences between them, for example in SCOPE and when its execution.

SCOPE:

  • Macro: has global scope.
  • Function: has a local scope whether you don't specify.

EXECUTION: it works like C++ or C

  • Macro: the variable names are replaced to strings before configuring.

  • Function: the variable names are replaced during execution.

In conclusion, add the PARENT_SCOPE flag in set command

set(PROTO_FILES ${PROTO_FILES} ${file_name} PARENT_SCOPE)

like image 148
uelordi Avatar answered Oct 26 '22 11:10

uelordi


Using a macro instead of a function seems to do it:

macro(generate_rpc file_name)
  set(PROTO_FILES ${PROTO_FILES} ${file_name})
endmacro(generate_rpc)

EDIT: According to http://www.cmake.org/cmake/help/syntax.html (should be in the man page, IMO):

CMake functions create a local scope for variables, and macros use the global scope.

like image 34
tibur Avatar answered Oct 26 '22 09:10

tibur