cmakeallegro5

How to use allegro5 in a cmake project?


I'm trying to include allegro5 in a cmake project.

find_package(PkgConfig REQUIRED)

include_directories(${PROJECT_SOURCE_DIR})
add_executable(app main.c)

pkg_check_modules(allegro-5 REQUIRED allegro-5)
target_link_libraries(app ${ALLEGRO5_LIBRARIES})
target_include_directories(app PUBLIC ${ALLEGRO5_INCLUDE_DIRS})

My main.c is:

#include <allegro5/system.h>

int main()
{
    al_init();
    return 0;
}

But when I run cmake --build . I get the following error:

main.c:(.text+0x14): undefined reference to `al_install_system'
collect2: error: ld returned 1 exit status

I'm looking for an example CMakeLists.txt file of an application that links with allegro5.


Solution

  • You almost have it except for a misunderstanding of pkg_check_modules().

    The first argument to pkg_check_modules() is a literal prefix that you choose. This will be the prefix to all the variables that pkg_check_modules() sets. If you had chosen "foo", the variables that would have been set would be foo_LIBRARIES, foo_INCLUDE_DIRS, foo_CFLAGS, etc.

    You chose the prefix "allegro-5", but in subsequent commands you're trying to use the varibales ALLEGRO_LIBRARIES and ALLEGRO5_INCLUDE_DIRS. These variables aren't set, because the variables that you actually want are allegro-5_LIBRARIES and allegro-5_INCLUDE_DIRS. Change those 3 three commands to:

    pkg_check_modules(ALLEGRO5 REQUIRED allegro-5)
    target_link_libraries(app ${ALLEGRO5_LIBRARIES})
    target_include_directories(app PUBLIC ${ALLEGRO5_INCLUDE_DIRS})
    

    or:

    pkg_check_modules(allegro-5 REQUIRED allegro-5)
    target_link_libraries(app ${allegro-5_LIBRARIES})
    target_include_directories(app PUBLIC ${allegro-5_INCLUDE_DIRS})
    

    Once you have the prefix given in pkg_check_modules() matching the variables you want to use, your project will build correctly. (Assuming of course, Allegro 5 is installed correctly.)