1

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.

zaijun
  • 45
  • 6

1 Answers1

1

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

Edit: the main program does contain a reference to the library but not to the needed object in the library, so that object (a.o) is not linked.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Is invoking `createPlugin` in main not considered a "reference" to the static plugin library? – zaijun Dec 05 '22 at 07:07
  • See the edit. You place `createPlugin` in a wrong place. It should be in the main program, not in any plugin library (otherwise you will have problems if you have more than one plugin). – n. m. could be an AI Dec 05 '22 at 07:41