4

I have a shared library (which currently compiles, loads and runs) mylib.so. From within this library, I want to use a new function (register it in another external library). The signature is bool my_function(const QVariant *, PyObject **).

This new function is defined in a separate .cpp file which is compiled to an object and then linked to mylib.so.

So I create a new OBJECT with my custom function

ADD_LIBRARY(helper_lib OBJECT helper_lib.cpp)

And include this when building my library

ADD_LIBRARY(mylib SHARED source.cpp $<TARGET_OBJECTS:helper_lib>)

It fails with an "undefined reference to `my_function'"

I can see that

  • The helper_lib.o file is generated
  • nm helper_lib.o shows

    0000000000000000 T _Z11my_functionPK8QVariantPP7_object

  • nm mylib.o shows

    U my_function

  • The helper_lib.o is passed to clang++ :

    clang++ -fPIC [...] -o my_lib.so mylib.o helper_lib.o [...]

I struggle to see where the mistake happens. I can imagine that there is something wrong in mylib.o which shows an unmangled symbol name which cannot be matched to the helper_lib.o symbol name, but I may as well be totally on the wrong track with this.


helper_lib.h

void my_function();

helper_lib.cpp

#include "helper_lib.h"

void my_function()
{
  return;
}

source.cpp is more complicated, as it contains mainly code automatically generated by sip.

Matthias Kuhn
  • 1,162
  • 2
  • 14
  • 42

1 Answers1

3

It works for me with a simple source.cpp. So it must be that something gets messed up during inclusion, you can try moving #include "helper_lib.h to the top of your source.cpp.

To verify that this has nothing to do with your toolchain, you can try from a clean build directory the following project:

CMakeLists.txt:

cmake_minimum_required(VERSION 3.3)
project(dummy)
ADD_LIBRARY(helper_lib OBJECT helper_lib.cpp)
ADD_LIBRARY(mylib SHARED source.cpp $<TARGET_OBJECTS:helper_lib>)

source.cpp:

#include "helper_lib.h"
void dummy() {
    my_function();
}

helper_lib.h:

#pragma once
void my_function();

helper_lib.cpp:

#include "helper_lib.h"
void my_function() {
}

Some documentation.

Antonio
  • 19,451
  • 13
  • 99
  • 197
  • 1
    That did it! [Sip](https://www.riverbankcomputing.com/software/sip/intro) was putting the `#include` in some other part of the code and I had to include it in a `%ModuleHeaderCode` section to get it to the proper location. Thanks a lot. – Matthias Kuhn May 11 '16 at 12:47