Relative path with #pragma comment(lib)

2019-03-26 00:23发布

问题:

Using Visual Studio 2010, I'd like to specify a path in a #pragma comment(lib) relative to the cpp file including it.

I tried

#pragma comment(lib, __FILE__"\\..\\foo.lib")

in foo.cpp and it seems to work. However, this appears hackish to me.

Is there a less hackish way?

回答1:

No, not if this needs to be relative from a .cpp file. Which is pretty unusual, you cannot normally guarantee that a .lib got deployed in a directory that's relative from a client source code that uses the library. Although you can certainly give install instructions that stipulate this.

The normal way is to just specify "foo.lib" and have the linker configured to search the proper directory for the .lib file with the Additional Library Directories setting. Which allows the .lib to be deployed anywhere but the library user will have to update the setting when he sets up his project. This is otherwise a very normal configuration task. And not terribly different from specifying the library in the Additional Dependencies setting.

Keep in mind that the #pragma is typically most useful to help the client programmer to use the proper version of a static link library. You normally have to provide 4 builds of a static .lib, debug vs release and /MT vs /MD. Possibly multiplied by the number of VS versions you are willing to support. This can get hairy in a hurry. The _DLL, _DEBUG and _MSC_VER predefined macros help you to generate the correct #pragma.