Search code examples
c++cstatic-linkingextern

Trying to use extern in reverse order


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?


Solution

  • Of course, you merely have to declare the function in the library.

    void onSomeEvent() {
        void doSomething(); // declares the function
        doSomething(); // call doSomething() here
    }