Search code examples
c++sdlsdl-2clion

undefined reference to `SDL_Init' in an external library


so i am making a class in an external library to use it in an SDL project. when using a single file sdl is linked correctly and works fine.But when i use the external library i get Screen.cpp:7: undefined reference to `SDL_Init' i use main.cpp, Screen.cpp and Screen.h this is Screen.h

#ifndef TEST_CLASSSDL_SCREEN_H
#define TEST_CLASSSDL_SCREEN_H
#include "C:/dev/i686-w64-mingw32/include/SDL2/SDL.h"
    class Screen {
    public:
        void init();
    };
#endif

and this is Screen.cpp

#include "Screen.h"
void Screen::init() {
SDL_Init(SDL_INIT_VIDEO);
}

and CMakeLists.txt (used by clion and very important here)

cmake_minimum_required(VERSION 3.15)
project(test_classSDL)
set(SDL2_LIB_DIR C:/dev/i686-w64-mingw32/lib)
include_directories(C:/dev/i686-w64-mingw32/include)

add_definitions(-DSDL_MAIN_HANDLED)
add_executable(${PROJECT_NAME}  ${SDL2_LIB_DIR}/libSDL2.dll.a
        ${SDL2_LIB_DIR}/libSDL2main.a ${SDL2_LIB_DIR}/libSDL2_image.dll.a main.cpp Screen.cpp Screen.h)

and thanks a lot for helping.


Solution

    1. Screen.h is not needed in add_executable.
    2. To tell compiler which library your target (i.e. executable) should link to, use target_link_libraries.

    Replace your last add_executable statement with:

    add_executable(${PROJECT_NAME} main.cpp Screen.cpp)
    target_link_libraries(
      ${PROJECT_NAME} ${SDL2_LIB_DIR}/libSDL2.dll.a ${SDL2_LIB_DIR}/libSDL2main.a
      ${SDL2_LIB_DIR}/libSDL2_image.dll.a)