Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在GNU GCC和clang中创建带有外部标头的共享库_C_Gcc_Clang_Cygwin - Fatal编程技术网

在GNU GCC和clang中创建带有外部标头的共享库

在GNU GCC和clang中创建带有外部标头的共享库,c,gcc,clang,cygwin,C,Gcc,Clang,Cygwin,对于我的这个问题,我的目标是创建一个软件,main,它包含一个插件,libfunc.so,和libfunc.so将修改burger的值 main.c: #include <stdio.h> #include <stdlib.h> // for exit() #include <dlfcn.h> #include "main.h" int burger = 3; int main(){ void (*ptr_func)();

对于我的这个问题,我的目标是创建一个软件,
main
,它包含一个插件,
libfunc.so
,和
libfunc.so
将修改
burger
的值

main.c

#include <stdio.h>
#include <stdlib.h> // for exit()
#include <dlfcn.h>
#include "main.h"

int burger = 3;

int main(){
   void (*ptr_func)();
   void *handle;

   handle = dlopen("./libfunc.so", RTLD_NOW);
   if (!handle) {
      fprintf(stderr, "%s\n", dlerror());
      exit(1);
   }

   *(void**)(&ptr_func) = dlsym(handle, "some_func");
   if (!ptr_func){
      fprintf(stderr, "%s\n", dlerror());
      dlclose(handle);
      exit(1);
   }

   printf("before ptr_func %d\n", burger);
   ptr_func();
   printf("after %d\n", burger);

   return 0;
}
插件[func.c]如下所示:

#include <stdio.h>
#include "main.h"

void some_func(){
   burger += 10;
}
但gcc的问题在于:

$ gcc -rdynamic main.c -o main
$ gcc -shared -fPIC func.c -o libfunc.so
/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: /tmp/cc
vgKpEc.o:func.c:(.rdata$.refptr.burger[.refptr.burger]+0x0): undefined reference
 to `burger'

是的,我已尝试删除
外部
,它已成功编译,但输出为:

$ ./main.exe
before ptr_func 3
after 3
另一方面,clang成功地编译了此文件,并按照我的预期工作:

$ ./main
before ptr_func 3
after 13
与在
clang

这两个对手真的不喜欢保持一致吗

这里是要点

附加说明: 我听到的叮当声来自特尔默斯。(模拟linux的android应用程序)。 我的gcc来自cygwin

gcc版本9.3.0

叮当9.0.0版

注意 在我的Termux中,我安装了gnu-8并编译了上面的MWE,但我没有遇到错误


也许我应该使用Windows.h来解决这个问题,而不是在cygwin中使用dlfcn.h。

尝试重新排序命令以编译:
$gcc-shared-fPIC-o libfunc.so func.c
这似乎是Windows上cygwin的问题。你能试试
-Wl,--out implib
选项吗,即
gcc-shared-fPIC func.c-o-Wl,--out implib libfunc.so
?@P.P“错误:libfunc.so:没有这样的文件或目录。”在我的cygwin中应该是(错放
-o
):
gcc-shared-fPIC func.c-Wl,--out implib-o libfunc.so
我还没有测试过,但在Linux上应该可以。尝试重新排序命令以编译:
$gcc-shared-fPIC-o libfunc.so func.c
这似乎是Windows上Cygwin的问题。你能试试
-Wl,--out implib
选项吗,即
gcc-shared-fPIC func.c-o-Wl,--out implib libfunc.so
?@P.P“错误:libfunc.so:没有这样的文件或目录。”在我的cygwin中应该是(错放
-o
):
gcc-shared-fPIC func.c-Wl,--out implib-o libfunc.so
我还没有测试过,但在Linux上应该可以。
$ ./main.exe
before ptr_func 3
after 3
$ ./main
before ptr_func 3
after 13