Linking SDL2 - CLion - Ubuntu 16.04 - G++

為{幸葍}努か 提交于 2021-01-28 11:03:10

问题


Background info

As the title says, I am on Ubuntu 16.04 using CLion and G++, and I am unable to link SDL2.

SDL2.h is found in the project at External Libraries/Header Search Paths/include/SDL2. This seems to link to /usr/include/SDL2.

So, with the header file found, I can #include <SDL2/SDL.h> without any issues. Yet, when I try to make use of SDL2 with something like, SDL_Init( SDL_INIT_EVERYTHING ), I get an undefined reference.

If I compile from terminal with g++ main.cpp -lSDL2 -o test I have no errors. But, if I compile from terminal with g++ main.cpp -o test, then I have the same error as CLion!

Question

How do I link SDL2 to Cmake? Did I add this flag -lsdl2 to the CMake file correctly? If I added it properly, then what am I missing?

main.cpp

#include <iostream>
#include <SDL2/SDL.h>

int main(int argc, char* argv[]) {
    SDL_Init( SDL_INIT_EVERYTHING );
    std::cout << "Hello, World!" << std::endl;
    SDL_Quit();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(untitled2)


set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lSDL2")

add_executable(untitled2 main.cpp)

回答1:


You just need to search for the SDL2 package and link it to the target. Don't use CMAKE_CXX_FLAGS for this (or any sort of linking/header paths/etc); try the following:

find_package(SDL2 REQUIRED SDL2)
 : 
add_executable(untitled2 main.cpp)
target_link_libraries(untitled2
  PRIVATE SDL2::SDL2
)

This will pull in the appropriate for headers etc. Note, this does not automatically include SDL_main or other libraries, which you may need or want in addition.

Additionally, for older versions of SDL2, SDL2::SDL2 may not work, and you may just want SDL2. I would recommend upgrading if this is the case, though.




回答2:


You can try

SET(CMAKE_CXX_LINK_FLAGS "-lSDL2")



回答3:


I modified the answer @rpav gave. This project has the minimal amount of code necessary to test that SDL2 was in fact working with CLion.

main.cpp

#include <iostream>
#include <SDL2/SDL.h>

int main(int argc, char* argv[]) {
    SDL_Init( SDL_INIT_EVERYTHING );
    std::cout << "Hello, World!" << std::endl;
    SDL_Quit();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(untitled2)
set(CMAKE_CXX_STANDARD 11)

find_package(SDL2 REQUIRED SDL2)

add_executable(untitled2 main.cpp)

target_link_libraries(untitled2 PRIVATE SDL2)

Most of the CMake file is provided by CLion. The only additional lines of code are find_package(SDL2 REQUIRED SDL2) and target_link_libraries(untitled2 PRIVATE SDL2). To clarify, untitled2, is the name of my project.



来源:https://stackoverflow.com/questions/52338274/linking-sdl2-clion-ubuntu-16-04-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!