2017-04-04 59 views
-2

我的目标是创建一个由C++创建的共享库。我想从C程序中调用该库中的函数调用共享.so中的函数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` 

然后,我写ac程序来调用compareTwoImages()f恩膏从共享库这样的:

#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 

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

+0

的问题是,你是不是与你共享库链接程序。仅仅因为在你的硬盘上有一些文件,使用你的代码使用的函数,并不意味着编译器会自动知道它在哪里。您必须显式链接该共享库(并确保它在共享库搜索路径中,在运行时)。请参阅'ld(1)''''''''''l'''文件,您可以通过gcc传递。 –

+1

其中之一,库-lcompareImage应该在c_call_cpp.c之后。 –

+0

谢谢Sam和Anon。我的错误是把它放在c_call_cpp.c之前的-lcompareImage,它现在可以工作。 –

回答

1

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

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

在这里,你简单地把链接标志在错误的地方:

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.

相关问题