“ multiple definition ”

I used LLVM to write a pass in which I defined a function FUNC by inheriting modulePass that would record information about other functions in the file. I then compile the library, but get a multiple Definition error. I know this is because compiling each module independently defines FUNC once, so I get an error. But I want to know what I can do to avoid this error and achieve my goal of inserting a function in every executable.

This comes down to linkage. If all the functions are the same and you want them merged into one then you should mark them linkonce. If they’re different then they should be marked internal (each module will use its own version and some will be renamed if necessary).

Well, that’s a good idea, but in the end I need to put this information together. If each module defines its own function, how do I call it when the executable is finally generated?

Or, I want to do it this way. Is it possible to do this: I write an additional dynamic library, mypasstest.o, in which I define the function FUNC. Then reference the library when compiling the individual files in the library and perform a statement insert (insert some information store in the current file) on the function FUNC in the library.

I tried it, but I didn’t know how to access functions defined in the dynamic library in pass, whose traversal can only access its own functions. Details are as follows:


for(auto F:M)
  StringRef func = F.g etName ();
  std: : string func_ = func. str ();
  if ( func_ == "FUNC") // It can only get functions from its own module, not FUNC
  {/* do something */}


void FUNC()
{ }

One solution might be to define a constructor function in each module (by adding it to the special @llvm.global_ctors variable. This variable has what seems to be the property you want: that each module’s contribution will be appended to the list and all those functions will be run when the executable (or dylib) is loaded.

That constructor could (for example) register its own module’s extra data with some single, central store that you can look up later. Or maybe you can use the contructor function to do what you want directly.

1 Like

Yes, I came up with this idea after my previous reply and implemented it. Thank you very much!