Reputation: 121
I'm looking to make a set of libraries that a developer can use, and they can decide if they want to use them as dynamic libraries, or static libraries. Of course, this brings up several issues of complexity, the current of which is symbol resolution. In my test code, I have 3 projects: The executable project, the static project, and the dynamic project. As the name implies, the static project is compiled to a .lib, and the dynamic project is compiled to a .dll.
The static project includes the header for the dynamic project's code, and calls the function DynamicFunction
, which means it will try to link to this function at compile time. However, the dynamic project being compiled to a shared library, it's not available, and it doesn't link. Is there a way for me to define the function, in any of the three projects, to resolve this issue?
My test code is as follows:
main.cpp - compiles to the executable
#include <Windows.h>
#include "../static/static.h"
using proc = void(*)();
proc p = 0;
// I tried using this to force there to be a DynamicFunction function to link with,
// But since they're in different compilation units, it doesn't quite work.
void DynamicFunction() {
if (p) {
p();
}
}
int main(int argc, char** argv) {
HMODULE dll = LoadLibrary("dynamic");
proc p = (proc)GetProcAddress(dll, "DynamicFunction");
UseDynamic();
}
Static.h
#pragma once
void UseDynamic();
Static.cpp
#include "../dynamic/dynamic.h"
#include "static.h"
void UseDynamic() {
DynamicFunction();
}
dynamic.h
#pragma once
extern "C" __declspec(dllexport) void DynamicFunction();
dynamic.cpp
#include "dynamic.h"
void DynamicFunction() {}
I recognize the error is stemming from UseDynamic
's assumption that the function is also defined statically, but I'm not aware of any way to have it be aware of whether or not the function is static or dynamic without having knowledge of how another library is being used, and even it would probably involve some ugly preprocessor conditionals.
Is is possible to do what I'm looking to do, or would I need to decide on either static or dynamic libraries (or at the least, not allow mixing the two)
Edit: I'm working with Visual Studio 2017
Upvotes: 1
Views: 2062
Reputation: 30494
When you build a DLL project in Visual Studio, it will build a static import library along with the DLL. This library contains shim definitions of the functions your DLL exports that will take care of loading them from the DLL. Linking your test executable to your DLL's import library should get things working.
Upvotes: 1