Home >Backend Development >C++ >How to Solve Undefined Reference Error When Using SDL2 and SDL_image with CMake?

How to Solve Undefined Reference Error When Using SDL2 and SDL_image with CMake?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 19:46:02832browse

How to Solve Undefined Reference Error When Using SDL2 and SDL_image with CMake?

How to Use SDL2 and SDL_image with CMake (Solved Errors)

In this guide, we'll provide a solution for the issue faced when trying to use SDL2 and SDL_image with CMake.

Original Problem:

When attempting to compile a C program using SDL2 and SDL_image with CMake, an undefined reference to IMG_LoadTexture was encountered.

Improved Solution:

To address this issue, we can modify the CMakeLists.txt as follows:

<code class="cmake">project(shooter-cmake2)

cmake_minimum_required(VERSION 2.8)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")

add_executable(${PROJECT_NAME} src/test.cpp)

INCLUDE(FindPkgConfig)

PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)

INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})</code>

Explanation:

  • We use FindPkgConfig to locate and use the appropriate system libraries.
  • PKG_SEARCH_MODULE is used to search for SDL2 and SDL2_image and configure their include paths and libraries.
  • Notice that the Name value in /usr/lib/x86_64-linux-gnu/pkgconfig/SDL2_image.pc matches the third parameter to PKG_SEARCH_MODULE for this library.

Implementing these changes should resolve the linking issue and allow the program to use SDL2 and SDL_image successfully.

The above is the detailed content of How to Solve Undefined Reference Error When Using SDL2 and SDL_image with CMake?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn