【问题标题】:Undefined references when using SDL2 with Cmake/Linux/C++将 SDL2 与 Cmake/Linux/C++ 一起使用时未定义的引用
【发布时间】:2020-04-17 11:38:48
【问题描述】:

您好,

我试图在 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 是来自 SDL2 的 separate library
  • 我不知道,抱歉。但是当我试图在 CMakeLists.txt 中链接它时,会发生错误: CMakeLists.txt:17 (find_package) 的 CMake 错误:通过在 CMAKE_MODULE_PATH 中未提供“FindSDL_MIXER.cmake”,此项目已要求 CMake 查找包配置“SDL2_MIXER”提供的文件,但 CMake 没有找到。找不到由“SDL_MIXER”提供的具有以下任何名称的包配置文件:SDL_MIXERC​​onfig.cmake sdl_mixer-config.cmake

标签: c++ linux build cmake sdl


【解决方案1】:

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 将预先配置正确的包含和链接器路径。

【讨论】:

    猜你喜欢
    • 2015-04-08
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多