CMake/C Plugins for Loadable Commands: Difference between revisions

From KitwarePublic
Jump to navigationJump to search
(How to use CMake's load_command command, in this case to cause CMake to exit with status 42 (as a useless example!). I think that using load_command is generally a bad idea.)
 
(Replace content with link to new CMake community wiki)
 
(7 intermediate revisions by 5 users not shown)
Line 1: Line 1:
The normal way to add a new command to CMake is to just define a new macro or function (with the <tt>macro</tt> and <tt>endmacro</tt> or <tt>function</tt> and <tt>endfunction</tt> commands).
{{CMake/Template/Moved}}


The other way is to use the <tt>load_command</tt> command, but how does this command work? Actually, this command allows you to code a new CMake command in C or C++, and dynamically load the command into a running CMake. It effectively allows you to insert your own C or C++ code into CMake. The C plugin interface is actually a good example of design of a plugin interface, but it is difficult to use, it has almost no documentation (before the creation of this wiki page), it has several quirks and limitations, it seems leftover from an ancient CMake version, though it remains present in CMake 2.6.
This page has moved [https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/C-Plugins-for-Loadable-Commands here].
 
Avoid this feature! Coding a plugin and using <tt>load_command</tt> is probably not a good idea. This wiki page is for those readers who wonder about <tt>load_command</tt> or who want to experiment with it. Also, anyone can edit the page and add more information.
 
== Overview ==
The [http://public.kitware.com/cgi-bin/viewcvs.cgi/Source/cmLoadCommandCommand.cxx?root=CMake&view=log cmLoadCommandCommand.cxx] source file implements a <tt>load_command</tt> command, which takes the form of
 
load_command(SomeName dir1 dir2 ...)
 
This command prefixes "cm" to SomeName, and then loads a cmSomeName module into CMake. (For ELF systems, this would [http://www.freebsd.org/cgi/man.cgi?query=dlopen&sektion=3 dlopen(3)] a "libcmSomeName.so" file into CMake.) It searches for the module in the dir1, dir2, ... directories. Then it looks for and immediately calls the SomeNameInit function in the module.
 
One can code the module in C or C++, but it must include the [http://public.kitware.com/cgi-bin/viewcvs.cgi/Source/cmCPluginAPI.h?root=CMake&view=log cmCPluginAPI.h] file, which defines the interface from the module to CMake. The SomeNameInit function must use this interface to define one and only one new CMake command.
 
== EXIT example ==
How to make CMake exit with status 42?
 
Wrap the [http://www.freebsd.org/cgi/man.cgi?query=exit&sektion=3 exit(3)] C function as a CMake command. For example,
 
# in CMakeLists.txt
exit(42)
 
should immediately cause CMake to exit with the given status. This also skips the usual cleaning and error messages, so the <tt>exit</tt> command will never be useful in any actual CMake project. The <tt>exit</tt> command intends only a simple example of something that not any macro or function can do.
 
=== cmExitCommand.c ===
This is a C plugin. The entire source is in one file <tt>cmExitCommand.c</tt> which contains the following:
 
<pre>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include <cmCPluginAPI.h>
 
void ExitCommandInit(cmLoadedCommandInfo *);
static int ipass(void *, void *, int, char *[]);
 
void
ExitCommandInit(cmLoadedCommandInfo *info) {
        info->Name = "exit";
        info->InitialPass = ipass;
}
 
int
ipass(void *in, void *mf, int argc, char *argv[]) {
        cmLoadedCommandInfo *info;
        int status;
 
        info = (cmLoadedCommandInfo *) in;
 
        if (argc != 1) {
                info->Error =
                    strdup("called with incorrect number of arguments");
                return 0;
        }
 
        if (sscanf(argv[0], "%d%*c", &status) != 1) {
                info->Error =
                    strdup("requires an integer argument");
                return 0;
        }
 
        exit(status);
        /* NOTREACHED */
        return 1;
}
</pre>
 
That was the entire source code for the <tt>exit</tt> command. This module does not make any API calls back to CMake (no use of <tt>info->CAPI</tt> in the code), but it already demonstrates how to cause a command to do something, and how to report errors.
 
==== ExitCommandInit ====
CMake calls the ExitCommandInit function immediately after loading the module. The rule is that a module called cm''SomeName'' needs a ''SomeName''Init function; so a cmExitCommand module needs an ExitCommandInit function. This function must take a pointer to a struct. Here again is the code to ExitCommandInit:
 
<pre>
void
ExitCommandInit(cmLoadedCommandInfo *info) {
        info->Name = "exit";
        info->InitialPass = ipass;
}
</pre>
 
How to write the ExitCommandInit function? CMake initializes all <tt>info</tt> fields to zero (except <tt>info->CAPI</tt>), so this function needs only to set the interesting fields. The most important field is <tt>info->Name</tt> to the name of the command.
 
Every command has an InitialPass and a FinalPass. Most commands need only the InitialPass, a function that takes four arguments (void *info, void *mf, int argc, char *argv[]).
 
==== InitialPass ====
The declaration for InitialPass uses void *info instead of cmLoadedCommandInfo *info. The code uses a cast to avoid a warning in some compilers.
 
<pre>
        info = (cmLoadedCommandInfo *) in;
</pre>
 
InitialPass returns an int value, to be nonzero if the command succeeds, or zero if it fails.
 
The correct way to report an error is to set the info->Error string. For some strange reason, CMake will try to free(3) the string later. If you simply assign a string, then CMake will later pass a bogus pointer to free(3). Instead you need to [http://www.freebsd.org/cgi/man.cgi?query=malloc&sektion=3 malloc(3)] the string somehow; this is the reason for the [http://www.freebsd.org/cgi/man.cgi?query=strdup&sektion=3 strdup(3)] calls. After you set the error string, you can return 0 to make the command fail.
 
Also, CMake prepends the name of the command to the error message, so "called with incorrect number of arguments" becomes "''exit'' called with incorrect number of arguments".
 
The "exit" command needs two error checks; one to check the number of arguments, and another to check that the argument is an integer. (Though builtin CMake commands use [http://www.freebsd.org/cgi/man.cgi?query=atoi&sektion=3 atoi(3)] without an error check.)
 
<pre>
        if (argc != 1) {
                info->Error =
                    strdup("called with incorrect number of arguments");
                return 0;
        }
 
        if (sscanf(argv[0], "%d%*c", &status) != 1) {
                info->Error =
                    strdup("requires an integer argument");
                return 0;
        }
</pre>
 
=== Compiling a module ===
The cmExitCommand.c file leaves a problem. CMake cannot load a C source file directly, CMake can only load a compiled module.
 
The output of <tt>cmake --help-command load_command</tt> suggests using <tt>try_compile</tt> to compile the module, but <tt>try_compile</tt> only compiles executables (because it uses <tt>add_executable</tt>). So you need to create a separate CMake project for the cmExitCommand module, and build this project before loading the cmExitCommand module into any other project.
 
: (It might be possible to trick <tt>try_compile</tt> to build a module, or at least build an executable that exports its symbols like a module, if you pass the correct compiler flags after the COMPILE_DEFINITIONS keyword. However this would require to discover the correct compiler flags.)
 
Also, the compiler needs to find the <tt>cmCPluginAPI.h</tt> header file. CMake installs a copy in <tt>${CMAKE_ROOT}/include</tt>.
 
The following <tt>CMakeLists.txt</tt> file is enough to corectly build the cmExitCommand module:
 
cmake_minimum_required(VERSION 2.6)
project(ExitCommand C)
include_directories(${CMAKE_ROOT}/include)
add_library(cmExitCommand MODULE cmExitCommand.c)
 
The name of the cmExitCommand.c file is not important; but the name of the cmExitCommand target needs to match with the name of the ExitCommandInit function.
 
Put this <tt>CMakeLists.txt</tt> and <tt>cmExitCommand.c</tt> in one directory. Configure and build this project, then you have a module to try to load in CMake.
 
=== Testing the module ===
With the compiled module, one can try to load it in a CMake project with <tt>load_command</tt> and use the new command. Because <tt>load_command</tt> is not scriptable, you cannot use a cmake -P script to test a module. You must create a test CMake project.
 
The following <tt>CMakeLists.txt</tt> file is such a project:
 
cmake_minimum_required(VERSION 2.6)
project(exam C)
# replace ../work with path to module
load_command(ExitCommand ../work)
exit(freeway)
exit(19 left)
exit(42)
 
When this script runs, the <tt>load_command</tt> succeeds. The first two <tt>exit</tt> commands cause errors. The third such command exits CMake (and skips the usual error message about failing to configure the project). Unix users can use the command <tt>echo $?</tt> to check the exit status from CMake:
 
<pre>
unix$ cmake .
-- The C compiler identification is GNU
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
CMake Error at CMakeLists.txt:4 (exit):
  exit requires an integer argument
 
 
CMake Error at CMakeLists.txt:5 (exit):
  exit called with incorrect number of arguments
 
 
unix$ echo $?
42
unix$
</pre>
 
That was the story of how, after coding a C plugin, compiling a module and loading the module into CMake, we caused CMake to exit with status 42.
 
== Another Example? ==
Anyone can edit this wiki page and add more information. The person who wanted to bother could post or link an example of a plugin that actually used <tt>info->CAPI</tt> for something.
 
[[Category:CMake]]

Latest revision as of 15:40, 30 April 2018


The CMake community Wiki has moved to the Kitware GitLab Instance.

This page has moved here.