Home > Enterprise >  C pluggable source files not linked
C pluggable source files not linked

Time:12-05

I write software with plugins that can be abled or disabled in compile time. In its source file, a plugin registers itself by declaring a static const registry variable whose constructor adds the plugin's creator to a table. The main part of the program doesn't call a plugin's method directly.

For example, in PluginRegistry.cpp

struct PluginDesc {
    PluginDesc(std::string_view name,
               std::string_view desc): mName(name), mDesc(desc) {
        regPlugin(this);    // add instance to table
    }
    
    std::string_view name;
    std::string_view desc;
}

and in a plugin file PluginA.cpp

static const desc = PluginDesc("pluginA", "a plugin");  // try to register itself

But I cannot create any plugin even if Ninja shows it's been compiled unless I include the plugin's header and use some functions declared in it. Is it a result of the linker's optimization? If I have to include all plugins' headers, it's not pluggable anymore. How can I fix it?

Update: If the program link plugin library as static link, the creation will always fail, but dynamic link has no problem.

CodePudding user response:

You are placing your plugin in a static library, while your main program contains no references to that library. The library will not be linked by default.

You have several options:

  • place plugins in object files rather than libraries
  • use gcc flag -Wl,--whole-archive at the linking stage as explained e.g. here
  • place plugins in dynamic libraries and load them at run time
  •  Tags:  
  • c
  • Related