getting projectDir as a string or char* in c++

2019-06-24 10:54发布

I saw a couple of questions relevant to this topic, but I didn't found the easy and common way to do this.

My question is: How can I have $(projectDir) or another Macro as a string or char* in my C++ code?

Thanks

3条回答
在下西门庆
2楼-- · 2019-06-24 11:24

The &(projectDir) string can't directly passed to the program. Instead, you can get the directory where your executable was launched with GetCurrentDirectory(), well explained in Microsoft site:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa364934(v=vs.85).aspx

You'll get a *char string. Then you can move throught the directories with simple strings operations.

查看更多
何必那么认真
3楼-- · 2019-06-24 11:33

MYMACRO=R"($(ProjectDir))"; prefectly works for me.

I was in need of this for a long time and this came as a perfect solution. My test cases took input file path relative to $(ProjectDir) while running the exe tried to locate the input file path relative to the bin folder. As a result, I could have either the VS project happy or the exe, but not both.

This solution worked perfectly to make both of them happy.

Thanks @mvidelgauz for the valuable info.

查看更多
在下西门庆
4楼-- · 2019-06-24 11:40

If your compiler supports raw strings then you can add MYMACRO=R"($(ProjectDir))"; to preprocessor definitions (screenshot from Visual Studio 2013): enter image description here

Then you can add the following to your code:

#pragma message("MYMACRO == " MYMACRO) // will print project dir during compilation


std::cout << MYMACRO << std::endl; //will print project dir at run time
查看更多
登录 后发表回答