Visual C++ - the client of a library is unaware that the library has changed using pragma comment lib

113 views Asked by At

The codebase I am working with uses pragma comment lib to express the dependencies of code to the library that it needs. Its build is very broken. I made an experiment to try to understand the use of pragma comment lib. It is the simplest library and client of the library that I could produce.

Foo.lib
foo.cpp 
void foo() { printf("hello\n"); }
foo.h : 

#pragma comment(lib, "foo.lib")
void foo();

FooTest.exe
main.cpp : 

#include "foo.h"
void main()
{
    foo();
}

I am using Visual Studio 2005 (for compatibility with a big commercial program that only accepts plugins made with this version). The problem is that FooTest.exe does not recompile when foo.lib is updated. I make a change to foo.cpp, save, build. Then build the fooTest.exe solution. The fooTest.exe solution does not seem to understand that its dependency has been changed.

I can get around this problem by adding the linker dependency to FooTest.exe but that defeats the entire point of pragma comment lib.

I have read many posts about pragma comment lib and figure it is working for lots of people. In my overall codebase and my test it is not working. I must be missing something.

Scott

2

There are 2 answers

0
Khouri Giordano On

The comment lib pragma inserts a linker directive. The linker sees this and adds that library to its list of inputs. That is all it does. What you want is a project dependency, which you seem to know how to configure.

Visual Studio 2005 pragma comment documentation

0
Ofek Shilon On

This is a known limitation of MSBuild (the build engine behind VS2010+ versions) and most probably of VCBuild (the engine in VS2005 builds), and really to every reasonable build engine:

Dependency analysis receives as input only the project files - either vcproj, vcxproj, make files or whatever. If you inject the dependency into the source files (with #pragma lib), you are making it invisible to the build system altogether, thereby bypassing its dependency analysis and preventing a needed build when the dependency changes.

It is good practice to use pragma-comment-lib to express dependencies only on very stable components. If you occasionally do need to respond to changes in the component, pragma lib is just not the tool for you.