Thinh Tran
Thinh Tran

Reputation: 836

IMG_Load() doesn't work properly when using with CMake

I'm trying to make a game on vscode with CMake. Everything was fine until I try to show a png image on the screen. I had initialized and linked everything correctly and there are no errors that occur except this:

"Couldn't open ./Images/Mountain.png"

Here is my code:

#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#undef main

SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *tex;
int main(int argc, char const *argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        std::cout << "Initialize SDL" << std::endl;
        window = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 640, SDL_WINDOW_SHOWN);
        if (window)
            std::cout << "Window created" << std::endl;
        renderer = SDL_CreateRenderer(window, -1, 0);
        if (renderer)
        {
            std::cout << "Render created" << std::endl;
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
        }
        SDL_Surface *tempSurface = IMG_Load("./Images/Mountain.png");
        if (!tempSurface)
            std::cout << "Can't load image! Error: " << IMG_GetError() << std::endl;
        tex = SDL_CreateTextureFromSurface(renderer, tempSurface);
        SDL_FreeSurface(tempSurface);
    }
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_Quit();
    return 0;
}

And here is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.19)
project(SDL2 VERSION 1.0.0)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
set(SDL2_PATH "E:\\Code\\SDL2")
set(SDL2_IMAGE_PATH "E:\\Code\\SDL2")
set(SDL2_TTF_PATH "E:\\Code\\SDL2")
find_package(SDL2 REQUIRED)
find_package(SDL2_image REQUIRED)
find_package(SDL2_ttf REQUIRED)
include_directories(
    ${SDL2_INCLUDE_DIR} 
    ${SDL2_IMAGE_INCLUDE_DIRS} 
    ${SDL2_TTF_INCLUDE_DIR})
set(SOURCES
    src/main.cpp
    )
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(
    ${PROJECT_NAME}
    ${SDL2_LIBRARY}
    ${SDL2_IMAGE_LIBRARIES}
    ${SDL2_TTF_LIBRARIES}
)

I use Visual Studio Build Tools 2019 Release - x86 kit for CMake and build it successfully with CMake extension. The error only appears when I run the program although my path is correct.

Upvotes: 1

Views: 309

Answers (0)

Related Questions