从 C 调用共享 .so 中的函数

Call a function in shared .so from C

我的目标是创建一个从 C++ 创建的共享库。我想从 C 程序中调用该库中的函数

我有一个 compareImage.h:

#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif

EXTERNC int compareTwoImages();

#undef EXTERNC

和一个 compareImage.cpp 文件:

#include "SURF_Homography.h"
extern "C" int compareTwoImages(){
  ..
}

我已经使用这个命令创建了一个共享库:

g++ -ggdb `pkg-config --cflags opencv` -fpic -shared compareImage.cpp -o libcompareImage.so `pkg-config --libs opencv` 

然后,我编写了一个 c 程序来从共享库中调用 compareTwoImages() 函数,如下所示:

#include <stdio.h>

int main() {
   /* my first program in C */
   int test = compareTwoImages();
   printf("Comparison Results: %d\n", test);

   return 0;
}

并用这个命令编译它:

gcc -lcompareImage c_call_cpp.c -o callCpp.o

但是显示错误:

/tmp/cc0wuZTU.o: In function `main':
c_call_cpp.c:(.text+0xe): undefined reference to `compareTwoImages'
collect2: error: ld returned 1 exit status

所以我不知道是什么问题。

问题不在于 C++ 或您的共享库或类似的东西。

下次将您的问题缩小到一个简单的例子。

这里你只是把link标志放在了错误的地方:

gcc -lcompareImage c_call_cpp.c -o callCpp.o
#   ^^^^^^^^^^^^^^

它需要在 将使用其符号的对象之后。

gcc c_call_cpp.c -o callCpp.o -lcompareImage

这在the documentation for -l中有明确说明:

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded.