0

Sorry for not knowing much about C++. There is a problem I can't solve. I want the CONFIG_PATH variable to be dynamic, not fixed. I want it to be replaceable from the outside, but I've never been able to.

string custom_path;

custom_path= argv[i];

I want to replace CONFIG_PATH with custom_path. Or I want to set it as CONFIG_PATH + custom_path

#define CONFIG_PATH "D:/config"

int GetConfigPath(char *path, size_t size, const char *name)
{
    if (!OBS_UNIX_STRUCTURE && portable_mode) {
        if (name && *name) {
            return snprintf(path, size, CONFIG_PATH "/%s", name);
        } else {


            return snprintf(path, size, CONFIG_PATH);
        }
    } else {
        return snprintf(path, size, CONFIG_PATH "/%s", name);
    }
}
SweetNGX
  • 153
  • 1
  • 9

2 Answers2

4

I want the CONFIG_PATH variable to be dynamic

CONFIG_PATH isn't a variable in the example. It is a pre-processor macro. It isn't possible to change pre-processor macros at runtime.

You can replace the macro with a variable whose value can be changed at runtime. Example:

std::string CONFIG_PATH;

int main(int argc, char** argv)
{
    CONFIG_PATH = argv[i];

As a side-note: Global variables are potentially problematic. Consider alternative designs like for example passing the value as a parameter into the function.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

If you remove the #define and instead use std::getenv("CONFIG_PATH") you can export (or whatever it's called in your shell) an environment variable named CONFIG_PATH that you can then read in your program. You must export it before running the program and any changes you make to it outside of your program will not be visible.

You can not concatenate it with other strings like you currently do with the macro though.

const char* config_path = std::getenv("CONFIG_PATH");
if(config_path) {
    std::string path_to_foo = std::string(config_path) + "/foo";
    // use path_to_foo ...
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108