Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code in CMake

I've got the following piece of code which gets the current system IP and stores it in the SERVER_IP variable:

EXECUTE_PROCESS(
    COMMAND ip route get 8.8.8.8
    COMMAND awk "NR==1 {print $NF}"
    OUTPUT_VARIABLE SERVER_IP
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

I need to use this IP several places in my CMakeLists.txt file hierarchy. What's the best approach to reuse this code? My first thought is to make it a function like function(GetIP), but I am not sure where to put this function to make it visible to all CMakeLists.txt file.

like image 708
B Faley Avatar asked Oct 24 '25 01:10

B Faley


1 Answers

If you make the CMake function available in the top-level CMakeLists.txt file, it will be also available in the CMakeLists.txt files of the subdirectories you added with ADD_SUBDIRECTORY.

Either define the function directly in the top-level CMakeLists.txt file or use something like INCLUDE(GetIP.cmake) there.

like image 198
m.s. Avatar answered Oct 25 '25 21:10

m.s.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!