Given this library:
lib1.h:
#pragma once
#include <windows.h>
void foo();
lib1.cpp
#include "lib1.h"
void foo() {
MessageBox(NULL, "XXX", "YYY1", MB_OK);
}
Created in the command line with the next commands:
cl /c lib1.cpp
lib lib1.obj
And then this little test:
#pragma comment(lib, "lib1")
#include "lib1.h"
void start() {
foo();
}
I've tried to run it on a windows vs2015 project setting:
But I'm facing a linker error such as:
main.obj : error LNK2019: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ) referenced in function "void __cdecl start(void)" (?start@@YAXXZ)
I've tried changing the pragma comment to #pragma comment(lib, "lib1.lib")
, #pragma comment(lib, ".\\lib1.lib")
, #pragma comment(lib, "./lib1.lib")
and none of them worked.
I've also tried to include in the linker additional paths the path of lib1.lib and then using either #pragma comment(lib, "lib1.lib")
or ``#pragma comment(lib, "lib1.lib")`, no luck.
In fact, the funny thing is, when turning on the /VERBOSE in the linker I don't see any linker's attempt to use the #pragma directive. Of course, If i added lib1.cpp or lib1.lib to the project it'd work but I'm trying to figure out how to use the pragma directive... So, anyone could explain what's going on here and how to solve this issue?
Don't use /NODEFAULTLIB
, it basically instructs the linker to ignore all #pragma comment(lib, ...)
. Explanation from here for instance:
When you use #pragma comment(linker) or #pragma comment(lib) you get a special entry in the object file (it's a special COFF section usually named ".drectve" with the directive bit set). Once the linker sees this entry it treats it as if the switch was given on the linker command line.
So:
t.cpp:
#pragma comment(lib,"advapi32.lib")
...
cl t.cpp
is equivalent to
t.cpp:
...
cl t.cpp /link /DEFAULTLIB:advapi32.lib
and when you add /NODEFAULTLIB
to that last comment it will ignore whatever is specified as /DEFAULTLIB
.
If you want to suppress individual libraries by giving their names to /NODEFAULTLIB:name.lib
that is still fine, though.