7

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

1
  • E.g. pass it as a macro symbol via compiler option /D (possibly you can just use the macro definitions in the project settings). In the C++ code you can then just use it. Jul 5, 2016 at 12:13

2 Answers 2

8

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
5
  • 1
    That looks to me like VS 2010, which I thought did not support raw strings. Am I wrong, or are you faking us out with the screenshot? Jul 5, 2016 at 12:55
  • 1
    Version of VS is not mentioned in the question, that's why I wrote "If your compiler supports raw strings" And no, I am not faking anyone here. I'll add comment to the answer now. And BTW screenshot will be practically the same in VS2010, just string won't work because of backslashes in the path
    – mvidelgauz
    Jul 5, 2016 at 13:05
  • 1
    I understand that. How did you get VS 2013 to look like VS 2010? How did you disable the horrible custom theme that modern versions of Visual Studio come with? Jul 5, 2016 at 13:14
  • 1
    @CodyGray I honestly have no idea, I didn't change anything. But I have "Ultimate" edition if that matters...
    – mvidelgauz
    Jul 5, 2016 at 13:31
  • 2
    @CodyGray: For VS 2013 there's a registry setting to turn off the all caps, and some more extensive copying and file creation (IIRC) to deal with the color scheme. Just google it. For the screenshots, to deal with round corners and multiple windows and menus and so on, I recommend (not free) WinSnap; I'm very happy with it, even though it's not perfect. Isn't it amazing that Microsoft has not managed to provide a decent general screenshot facility? Or, OK, thinking about it, that's not amazing. But. :) Jul 5, 2016 at 14:07
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.