Problem with clang plugin that does ast analysis compilation together


I want to write a plugin for Clang that ALSO allows me to compile. So far, I wrote a plugin for Clang that inspects the AST and prints some info (like many of me did before). But when it comes the time to compile, it breaks. Here is the plugin’s relevant code:

class MyPluginAction : public PluginASTAction {
          std::set<std::string> ParsedTemplates;
      std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) override {
        return ...; //return my unique_ptr<>
      // tests to make the plugin starting automatically, none of these opt work
      PluginASTAction::ActionType getActionType() override {
        // return Cmdline; ///< Action is determined by the cc1 command-line
        // return ReplaceAction; ///< Replace the main action
        return AddBeforeMainAction; ///< Execute the action before the main action
        // return AddAfterMainAction;  ///< Execute the action after the main action
      bool ParseArgs(const CompilerInstance &CI,
                     const std::vector<std::string> &args) override {        
        return true;
    static FrontendPluginRegistry::Add<MyPluginAction>
    X("myplugin", "mypluginAction desc..");

I managed to compile the plugin. Then I can run like this:

$clang++ sample.cpp  -Xclang -load -Xclang $PATH/ -Xclang -plugin -Xclang myplugin

However, doing that returns this errors when compiling:

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
clang-12: error: linker command failed with exit code 1 (use -v to see invocation)

Using -add-plugin instead of -plugin makes the compilation work, however, I notice my plugin is loaded without being executed. I.e., I know the classes of my plugin are instantiated because I used some logs. However, the actual analysis is not called. It seems like the plugin is not meant to be scheduled.

Any ideas?

Try to call your plugin like this:

clang++ -Xclang -add-plugin -Xclang your_plugin -fplugin=<path-to-your-plugin>.so -fplugin-arg-your_plugin-your-argument <file_to_parse>

For example:

$clang++ sample.cpp  -Xclang -add-plugin  -Xclang myplugin -fplugin=$PATH/