[CMake] Using cmake's UsePkgConfig

Antti S. Lankila alankila at bel.fi
Mon Jul 17 11:09:23 EDT 2006


Hey.

This is probably bit of a newbie question but good information about
cmake is hard to come by.

I wanted to build against GTK2 with cmake. The FindGTK module is only
capable of detecting GTK 1.x and proved to be useless. So, I opted to
use pkg-config, because it's probably what autotools uses as well.

This is a piece of programming that I was able to make to work. The
first part detects GTK1, and the next part detects GTK2. The defines are
used to adapt the .c sources for the minor interface differences between
the two.


FIND_PACKAGE(GTK)
IF (GTK_FOUND)
    INCLUDE_DIRECTORIES(${GTK_INCLUDE_DIR})
    ADD_DEFINITIONS(-DHAVE_GTK)
    MESSAGE("GTK 1.x found and used as GUI\n")
ELSE (GTK_FOUND)
    PKGCONFIG(gtk+-2.0 GTK2_INCLUDE_DIR GTK2_LINK_DIR GTK2_LINK_FLAGS
GTK2_CFLAGS)
    PKGCONFIG(gthread-2.0 GTHREAD_INCLUDE_DIR GTHREAD_LINK_DIR
GTHREAD_LINK_FLAGS+- GTHREAD_CFLAGS)

    IF (GTK2_INCLUDE_DIR)
        # ok, I can get compile work through CFLAGS
        SET(CMAKE_C_FLAGS "${GTK2_CFLAGS} ${GTHREAD_CFLAGS}")
        # but to include libraries I have to do these awful hacks
        # remove -l from in front of library
        STRING(REGEX REPLACE "-l" "" GTK_LIBRARIES "${GTK2_LINK_FLAGS}
${GTHREAD_LINK_FLAGS}")
        SEPARATE_ARGUMENTS(GTK_LIBRARIES)
        ADD_DEFINITIONS(-DHAVE_GTK2)
        MESSAGE("GTK 2.x found and used as GUI\n")
    ELSE (GTK2_INCLUDE_DIR)
        MESSAGE(FATAL_ERROR "GTK or GTK2 is required to build this
project.")
    ENDIF (GTK2_INCLUDE_DIR)
ENDIF (GTK_FOUND)

I'd like to focus on the part inside IF (GTK2_INCLUDE_DIR). As can be
seen, I'm "converting" the -lfoo -lbar type line from the link flags to
library names and then, eventually, passing the variable GTK_LIBRARIES
to the TARGET_LINK_LIBRARIES macro. Is there some easier macro to use
that goes into the link line without this parsing work to convert
things? This is obviously especially important if the link line happens
to contain other but -l parameters. (or if the library name contains -l,
such as "art-lgpl" ;-)

I'd obviously prefer to be able to use PKGCONFIG in a manner like this:

    PKGCONFIG(some-library SOME_LIBRARY)
    # defines many magic variables, x_FOUND, x_DIRECTORIES, x_CFLAGS,
x_LIBRARIES, etc.

    IF (SOME_LIBRARY_FOUND)
        ADD_DIRECTORIES(SOME_LIBRARY_DIRECTORIES) # include dirs:
-I/some/path/here
        ADD_CFLAGS(SOME_LIBRARY_CFLAGS) # additional cflags:
-D_REENTRANT, -msse or whatever
    ENDIF (SOME_LIBRARY_FOUND)

And finally when compiling, this should be done:

    TARGET_LINK_LIBRARIES(${targetname} SOME_LIBRARY_LIBRARIES)

What do you think? Is this possible?

-- 
Antti



More information about the CMake mailing list