Home > OS >  Why does the starting directory matter when launching a OpenGL executable?
Why does the starting directory matter when launching a OpenGL executable?

Time:11-26

I am doing a openGL porject and readering my shaders from .vert and .frag glsl files. I am using CMake with an extension for auto ninja file generation as well. This is my readfile code:

std::string readFile(const char *filePath) {
    std::string content;
    std::ifstream fileStream(filePath, std::ios::in);

    if(!fileStream.is_open()) {
        std::cerr << "Could not read file " << filePath << ". File does not exist." << std::endl;
        return "";
    }

    std::string line = "";
    while(!fileStream.eof()) {
        std::getline(fileStream, line);
        content.append(line   "\n");
    }

    fileStream.close();
    return content;
}

I spent a long time thinking I was crazy because from my build dir I was doing ./app/NAME_OF_APP.exe but the shaders were not being applied just black. It was only when I clicked on it from within the file explorer that it worked so I cd'ed into build/app/ and called ./NAME_OF_APP.exe and boom it worked. Why is this behavior happening? does the starting dir effect the relative pathing of the actual application? seems odd to me. thanks.

CodePudding user response:

If you run a program from a command line the current directory is whatever directory is current in that command prompt. If you run a program from explorer the current directory is the directory that houses the executable.

You could use a function like GetModuleFileName (with NULL as the hModule parameter) to get the path to the executable and then chop off at the last \ and then change to that directory and then the program would not depend on the directory the program is run from.

CodePudding user response:

If you use relative paths in your app, they would be relative to the folder containing executable by default. When you run it from the command like ./app/NAME_OF_APP.exe, it looks like your environment rewrites the working directory, so it looks for shaders in ..

It's not really nice solution in my opinion, but you can set up working directory from the code if it works for you.

Please, look at Change the current working directory in C

  • Related