Search code examples
c++linuxbuildcmakesdl

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


Hello,

I'm trying to use SDL2 in my C++ project under Linkux but have undefined references to core functions. I included the header files and set up the CmakeLists correctly (I think), so I don't understand why he does not find the functions.

My C++ code:

#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;
}

My errors:

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'

My 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})

Thanks for the help in advance!


Solution

  • SDL_Mixer comes with a pkg-config file, so you can use CMake's pkg-config support:

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

    The IMPORTED TARGET PkgConfig::SDL2_Mixer will be preconfigured with the correct include and linker paths.