Search code examples
ccmakeclionglib

Undefined references when included GLIB in clion using cmake


I am trying to write a notification service for gnome but cmake keeps outputting undefined reference errors when building. I am using clion IDE and glib2.0 libraries and running on Fedora workstation 30.

What I have tried so far is searching lots of stack overflow threads and googling for hours.

My CMakeLists.txt file, which is copied from another StackOverflow thread, is here:

cmake_minimum_required(VERSION 3.14)
project(gnome_notification C)

set(CMAKE_C_STANDARD 99)

include(FindPkgConfig)
pkg_check_modules(GLIB glib-2.0 REQUIRED)
include_directories(${GLIB_INCLUDE_DIRS})

set(SOURCE_FILES main.c)

add_executable(${PROJECT_NAME} ${SOURCE_FILES})
target_link_libraries(${PROJECT_NAME} ${GLIB_LIBRARIES})

My main.c file is here:

#include <stdio.h>
#include <gio/gio.h>
int main() {
    GApplication* application = g_application_new ("Test", G_APPLICATION_FLAGS_NONE);
    GNotification* notification = g_notification_new("Test Title");
    g_notification_set_body(notification, "Test body");
    g_notification_set_priority(notification, G_NOTIFICATION_PRIORITY_NORMAL);
    g_application_send_notification(application, "Test Id", notification);
    return 0;
}

The build yields undefined reference error:

/home/xgao/bin/Clion/bin/cmake/linux/bin/cmake --build /home/xgao/Desktop/gnome_notification/cmake-build-debug --target gnome_notification -- -j 4
-- Configuring done
-- Generating done
-- Build files have been written to: /home/xgao/Desktop/gnome_notification/cmake-build-debug
[ 50%] Linking C executable gnome_notification
/usr/bin/ld: CMakeFiles/gnome_notification.dir/main.c.o: in function `main':
/home/xgao/Desktop/gnome_notification/main.c:4: undefined reference to `g_application_new'
/usr/bin/ld: /home/xgao/Desktop/gnome_notification/main.c:5: undefined reference to `g_notification_new'
/usr/bin/ld: /home/xgao/Desktop/gnome_notification/main.c:6: undefined reference to `g_notification_set_body'
/usr/bin/ld: /home/xgao/Desktop/gnome_notification/main.c:7: undefined reference to `g_notification_set_priority'
/usr/bin/ld: /home/xgao/Desktop/gnome_notification/main.c:8: undefined reference to `g_application_send_notification'
collect2: error: ld returned 1 exit status
gmake[3]: *** [CMakeFiles/gnome_notification.dir/build.make:84: gnome_notification] Error 1
gmake[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/gnome_notification.dir/all] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/gnome_notification.dir/rule] Error 2
gmake: *** [Makefile:118: gnome_notification] Error 2

Solution

  • You need something like

    pkg_check_modules(GLIB glib-2.0 gio-2.0 REQUIRED)
    

    or additionally

    pkg_check_modules(GIO gio-2.0 REQUIRED)
    

    because GNotification is provided by libgio, which is a separate library from libglib, even though they both come from the same source tree.