Reputation: 5823
When we have an exe
or dll
and a static library
attached to it, we are able to use extern
keyword to access static library's variables
and/or functions
from the exe
or dll
. To make things simpler, let's assume ve have an exe
and a lib
attached to it.
What I am trying to do is to call a function of exe
from lib
.
Executable Code
void doSomething() {
// do something here
}
Static Linked Library Code
void onSomeEvent() {
doSomething(); // call doSomething() here
}
Vice versa is easy but I wonder if this can be done in a way like extern
keyword. Or what is the best method?
What comes to my mind is to pass a function pointer
(like void*
) to one of the functions
/ methods
in the lib
(probably to a class constructor). I think this should work but I don't want to touch library's code too much since library is not mine and can be replaced with newer versions. I can add/remove a few lines of code to it but I want to prevent from changing function interfaces.
What is the better way?
Upvotes: 3
Views: 193
Reputation: 1248
You may also declare it outside your function, you may have other functions need it.
void doSomething(); // declares the function
void onSomeEvent()
{
doSomething(); // call doSomething() here
}
void onSomeEvent2()
{
doSomething(); // call doSomething() here
}
Upvotes: 4
Reputation: 122391
Given the static library is (probably) meant to be used in many different programs, it's not uncommon to use the callback approach where the exe initialises the library and passes it one or more function pointers to use to do things (like logging messages, or whatever). If the exe doesn't pass in the function pointers (or passes them as NULL
) then the library can simply not call those functions and the library will work well in both environments.
This is much better than assuming the functions are always defined in the exe.
Upvotes: 1
Reputation: 32635
Of course, you merely have to declare the function in the library.
void onSomeEvent() {
void doSomething(); // declares the function
doSomething(); // call doSomething() here
}
Upvotes: 2