[gdal-dev] How do I set PROJ_LIB env variable inside my program?

Igor Belyakov belyakov-i at spsinf.ru
Fri Nov 1 12:37:07 PDT 2019


I have a little code snippet that checks if the PROJ data is accessible to GDAL:
        OGRSpatialReference r;
        r.importFromEPSG(4979);
        char * wkt;
        r.exportToWkt(&wkt);
        auto s = qgetenv("PROJ_LIB");
        if (wkt[0] == '\0') throw std::runtime_error("PROJ_LIB error");

This code resides in a dll linked with GDAL. The dll is loaded by QLibrary::load in a lightweight executable after I set PROJ_LIB and GDAL_DATA env variables like so:
        auto appDir = QCoreApplication::applicationDirPath();

        const QByteArray projlib( QDir::toNativeSeparators(
                          appDir + "/libs/GDAL/PROJ_DATA" ).toStdString()
                                                           .c_str()
                                );
        qputenv("PROJ_LIB", projlib);

        const QByteArray gdaldata( QDir::toNativeSeparators(
                           appDir + "/libs/GDAL/GDAL_DATA" ).toStdString()
                                                            .c_str()
                                 );
        qputenv("GDAL_DATA", gdaldata);

The executable is not linked with GDAL, so I figure that GDAL and PROJ are launched after environment variables are set.

I know that the variable "s" after "auto s = qgetenv("PROJ_LIB");" (see the first code snippet) contains a valid path to a folder where all proj data resides. If I set that path to PROJ_LIB env variable in Windows (not in my code), everything works fine and "PROJ_LIB error" exception doesn't appear. But I want my program to operate without making the user to do any global environment changes and without launching .bat scripts that make the user see a console window.

I just tried it in release build and it works without rising the exception. It just doesn't work in debug. So we can use environment variables on developer machines and distribute without any .bat files or intervening in global system settings. But it doesn't seem to be very reliable decision. I don't understand why a "putenv" approach doesn't work in debug build.


More information about the gdal-dev mailing list