0

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.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • You can try by using the find scripts [here](https://github.com/tcbrindle/sdl2-cmake-scripts). I don't think you really want absolute paths in `#include`.. – Jack Jan 20 '20 at 23:33

1 Answers1

1
  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)

Zheng Qu
  • 781
  • 6
  • 22
  • ***Screen.h is not needed in add_executable.*** For some IDEs (like Visual Studio) it's desirable to add header files to the target. The reason if you don't the header does not appear as part of the project in the IDE (making navigation more difficult).With that said I do realize this question was tagged as clion – drescherjm Jan 20 '20 at 23:44
  • @drescherjm Can you please give a reference about that? I haven't worked with Visual Studio or Clion. – Zheng Qu Jan 21 '20 at 00:11
  • 1
    Related to that: [https://stackoverflow.com/questions/1167154/listing-header-files-in-visual-studio-c-project-generated-by-cmake](https://stackoverflow.com/questions/1167154/listing-header-files-in-visual-studio-c-project-generated-by-cmake) – drescherjm Jan 21 '20 at 00:20