'create shared library with main to call undefined function and provide function body in other project

I need to create a shared library using cmake, and I must call function run() in a library function. But the project which uses this library should provide the body of this function.

The real cases use systemC which force library to implement main function. To avoid further complexity, I try to simplify the case like this:

MyInterface.h

void run();

MyLibraryAction.cpp

#include "MyInterface.h"

int main(){
    run();
}

The cmake content is:

add_library(mylib SHARED MyLibraryAction.cpp)

set_target_properties(mylib PROPERTIES PUBLIC_HEADER MyInterface.h)

configure_file(mylib.pc.in mylib.pc @ONLY)

install(
  TARGETS mylib
  DESTINATION ${CMAKE_INSTALL_LIBDIR}
  PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
        DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

I am wondering if that is possible. If so, am I doing it right? is using extern relevant in this context? I am get error when I try to build and create the library:

undefined reference to run()



Solution 1:[1]

As mentioned in the comments, weak symbols worked fine in this case.

MyInterface.h

void run();

and then have an implementation for run function with weak symbol:

InterfaceWeakImplementation.h

void __attribute__((weak)) run(){
    // pass
}

and have the actual implementation in caller project

InterfaceStrongImplementation.h

void run(){
    // Some real work
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aryan Firouzian