将 SDL2 与 Cmake/Linux/C++ 一起使用时未定义的引用

Undefined references when using SDL2 with Cmake/Linux/C++

您好,

我正在尝试在 Linkux 下的 C++ 项目中使用 SDL2,但对核心函数有未定义的引用。我包含了头文件并正确设置了 CmakeLists(我认为),所以我不明白为什么他找不到函数。

我的 C++ 代码:

#include "SDL.h"
#include "SDL_mixer.h"
#include "SDL_image.h"

#include <iostream>
using namespace std;

#define NUM_WAVEFORMS 2
const char* _waveFileNames[] = {"Kick-Drum-1.wav", "Snare-Drum-1.wav"};

Mix_Chunk* _sample[2];

// Initializes the application data
int Init(void) {
    memset(_sample, 0, sizeof(Mix_Chunk*) * 2);

    // Set up the audio stream
    int result = Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 512);
    if( result < 0 ) {
        fprintf(stderr, "Unable to open audio: %s\n", SDL_GetError());
        exit(-1);
    }

    result = Mix_AllocateChannels(4);
    if( result < 0 ) {
        fprintf(stderr, "Unable to allocate mixing channels: %s\n", SDL_GetError());
        exit(-1);
    }

    // Load waveforms
    for( int i = 0; i < NUM_WAVEFORMS; i++ ) {
        _sample[i] = Mix_LoadWAV(_waveFileNames[i]);
        if( _sample[i] == NULL ) {
            fprintf(stderr, "Unable to load wave file: %s\n", _waveFileNames[i]);
        }
    }

    return true;
}

int main() {
    bool retval = Init();
    cout << retval << endl;
    return 0;
}

我的错误:

CMakeFiles/SDL_Test.dir/src/SDL_Test.cpp.o: In function `Init()':
/home/tamas/SDL_Test/src/SDL_Test.cpp:20: undefined reference to `Mix_OpenAudio'
/home/tamas/SDL_Test/src/SDL_Test.cpp:26: undefined reference to `Mix_AllocateChannels'
/home/tamas/SDL_Test/src/SDL_Test.cpp:34: undefined reference to `Mix_LoadWAV_RW'

我的CMakeLists.txt:

cmake_minimum_required (VERSION 3.5)

project (SDL_Test)

set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -std=c++11")
set (source_dir "${PROJECT_SOURCE_DIR}/src/")

file (GLOB source_files "${source_dir}/*.cpp")

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

add_executable (SDL_Test ${source_files})
target_link_libraries(SDL_Test ${SDL2_LIBRARIES})

提前感谢您的帮助!

SDL_Mixer自带一个pkg-config文件,所以你可以使用CMake的pkg-config支持:

include(FindPkgConfig)
pkg_check_modules(SDL2_Mixer REQUIRED IMPORTED_TARGET SDL2_mixer)
target_link_libraries(SDL_Test PkgConfig::SDL2_Mixer)

IMPORTED TARGET PkgConfig::SDL2_Mixer 将使用正确的包含和链接器路径进行预配置。