Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Failed to load image in MSVC  (Read 1395 times)

0 Members and 1 Guest are viewing this topic.

abcnb

  • Newbie
  • *
  • Posts: 12
    • View Profile
Failed to load image in MSVC
« on: October 20, 2022, 02:09:38 pm »
This
t1.loadFromFile("images/red.png");
:
1. Compiles.
2. Runs from Debug or Release directory.
3. Doesn't run inside MSVC.

This
t1.loadFromFile("C:\\Users\\User\\source\\repos\\SFMLtest\\x64\\Debug\\images\\red.png");
 
:
Works correctly in all cases.

Can somebody tell how to do it properly?

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: Failed to load image in MSVC
« Reply #1 on: October 20, 2022, 03:11:25 pm »
SFML's load functions are relative to the working directory of the program (when you don't give it an absolute path like "C:\\")
When you run a program from explorer, the working directory is set to where the exe file is.

Running a program from inside Visual Studio uses the working directory set in the project properties. Annoyingly, VS defaults all projects to having a working directory of where the vcxproj file is, instead of where the exe file is.

There's two ways to fix this:
1 - Go into project properties, Configuration Properties / Debugging / Working Directory and change it from $(ProjectDir) to $(TargetDir)
(TargetDir is the directory with the exe file, ProjectDir is the directory with the vcxproj file)
2 - Use Win32 to ask for the directory of where the program (the exe) is and change the working directory to that.

This is the code I use for the second option (since otherwise I always forget to change the project properties):
        char buf[MAX_PATH];
        GetModuleFileName(NULL,buf,MAX_PATH);

        std::string filename(buf);
        size_t backslash = filename.find_last_of('\\');
        if (backslash != std::string::npos)
        {
            filename = filename.substr(0, backslash);
        }
        SetCurrentDirectory(filename.c_str());
 

Sometimes you might want the ability to set different working directories externally, the second method will cancel out that and might therefore be unwanted.

abcnb

  • Newbie
  • *
  • Posts: 12
    • View Profile
Re: Failed to load image in MSVC
« Reply #2 on: October 21, 2022, 06:46:35 am »
Really many-many thanks. I assume that this is an offtopic about MSVC not SFML, but your answer with looking on projects settings from https://www.sfml-dev.org/download/sfml/2.5.1/ after CMake help so much.