1

I want to write a function in cmake.

it looks like:

macro(compile arg1)  # TODO here: define a endless input param
  target_link_libraries(${arg1} pthread zmq config++ mmm dl)   # TODO here: to add input list
endmacro(compile)

for example:

i want to compile a pragma named demo, it need library libb and libc

so i called: compile(demo, b, c)

please notice. the arg num is not fixed. so, i need a thing similar with char ** argv in c++

the first input parameter will set the binary file name, the left will be library name.

How can i do this? can you help on this? thanks

nick
  • 832
  • 3
  • 12
  • 1
    Just a note for future readers: This question is *not* about the C++ preprocessor and its macros, but the macros defined in a `CMakeLists.txt` file used by CMake itself. – Some programmer dude May 14 '21 at 09:18
  • 1
    @Someprogrammerdude But then the c++ tag is completely irrelevant here. – πάντα ῥεῖ May 14 '21 at 09:21
  • 1
    Please read [the `macro` documentation](https://cmake.org/cmake/help/latest/command/macro.html), especially [the section about arguments](https://cmake.org/cmake/help/latest/command/macro.html#arguments). Also note [the differences between macros and functions](https://cmake.org/cmake/help/latest/command/macro.html#macro-vs-function), especially when it comes to arguments. – Some programmer dude May 14 '21 at 09:21

1 Answers1

2

There's ARGN available which allows you to access all parameters after the last named one. Note that parameters are separated by one or more whitespace characters, not by commas for all cmake commands including macros.

macro(compile TARGET_NAME)
    target_link_libraries(${TARGET_NAME} pthread zmq config++ mmm dl ${ARGN})
endmacro(compile)

...

compile(demo b c)

Not sure if this case justifies creating a macro though, since you could simply do

target_link_libraries(demo pthread zmq config++ mmm dl b c)

Furthermore I do recommend specifying PRIVATE, PUBLIC or INTERFACE when linking libraries via target_link_libraries.

fabian
  • 80,457
  • 12
  • 86
  • 114