Search code examples
cmakemoduledirectoryheader

How to use CMake to get command line output as an argument?


I'm using CMake to build linux module mode, so I'm retrieving header files on ubuntu, currently I'm running ubuntu in docker and it has:

/lib/modules/4.15.0-76-generic

Well, several days later if I build a new image, it will become updated value:

/lib/modules/4.15.0-78-generic

So this number is changing, but there's only one directory under /lib/module, and it's not 'uname -a' output.

Linux 0a08e87c0a18 4.15.0-50-generic

So I wish to know if there's a convenient way in CMake just like shell ls /lib/module, and then I can use command line output as a parameter for header/library root directory?

Thanks a lot.


Solution

  • You can use CMake's file(GLOB ...) command to list the contents (files and sub-directories) within a particular directory. If the /lib/modules directory only contains one sub-directory (and no files), you could do something like this:

    file(GLOB MY_VERSIONED_DIR /lib/modules/*)
    

    You can now use the ${MY_VERSIONED_DIR} variable elsewhere in your CMake code, as it will be populated with the sub-directory path, for example:

    /lib/modules/4.15.0-78-generic
    

    You could also use CMake's execute_process() command, which runs commands in a child process during CMake configure-time. Use the OUTPUT_VARIABLE argument to capture the output of your command:

    if(UNIX)
        execute_process(
            COMMAND ls /lib/modules
            OUTPUT_VARIABLE MY_VERSIONED_DIR 
        )
    endif()