简体   繁体   中英

CMake “OBJECT” library: clang not linking properly

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM