简体   繁体   English

链接到包含全局变量的静态库时,clang 和 gcc-10 之间的不同行为

[英]Different behavior between clang and gcc-10 when linking to static library containing global variables

I have a statically linked library, containing a global variable barvar .我有一个静态链接库,其中包含一个全局变量barvar I can compile the library with no problems with either gcc-10 or clang (this is on macOS Catalina).我可以使用 gcc-10 或 clang(这是在 macOS Catalina 上)毫无问题地编译库。 Interestingly, the behavior differs between the two when I try to link it into a program that uses the library.有趣的是,当我尝试将其链接到使用该库的程序时,两者的行为有所不同。 Here's the code:这是代码:

In globvars.h , int barvar is declared:globvars.h ,声明了int barvar

#ifndef H_GLOBVARS_H                              
#define H_GLOBVARS_H                             
  
extern int barvar;                              

#endif  

In globvars.c , int barvar is defined:globvars.c ,定义了int barvar

#include "globvars.h" 
int barvar;

In foo.c , the function foo sets and prints barvar :foo.c ,函数foo设置并打印barvar

#include <stdio.h>
#include "globvars.h"
void foo() 
{
    barvar = 10;      
    printf("barvar is: %d\n", barvar);
    return; 
}

Here's test.c , the program that uses the library:这是test.c ,使用库的程序:

void foo(); 
int main(int argc, char **argv)
{     
    foo();            
    return 0;
} 

When I compile and link with gcc-10, no problems:当我用 gcc-10 编译和链接时,没有问题:

gcc-10 -c foo.c -o foo.o
gcc-10 -c globvars.c -o globvars.o
gcc-10 -c test.c -o test.o
gcc-ar-10 rcs liblinktest.a foo.o globvars.o
gcc -o testlinkrun test2.o -L. -llinktest

When I compile and link with clang, I get an undefined symbol error at the last step:当我用 clang 编译和链接时,我在最后一步得到一个未定义的符号错误:

cc -c foo.c -o foo.o
cc -c globvars.c -o globvars.o
cc -c test.c -o test.o
ar rcs liblinktest.a foo.o globvars.o
cc -o testlinkrun test2.o -L. -llinktest

with error:有错误:

Undefined symbols for architecture x86_64:
  "_barvar", referenced from:
      _foo in liblinktest.a(foo.o)

Any ideas?有任何想法吗? Interestingly, it appears the only step that has to be done with gcc-10 is compiling globvars.c .有趣的是,似乎必须与GCC-10编译完成的唯一步骤globvars.c I can use clang and the clang linker for all other steps, and everything is fine.我可以在所有其他步骤中使用 clang 和 clang 链接器,一切都很好。 Is it possible that clang is optimizing away all the variables in globvars.c ? clang 是否有可能优化掉globvars.c所有变量? How can I prevent this?我怎样才能防止这种情况?

As @EricPostpischil observed in this comment , the issue is that clang defaults to treating barvar as a common symbol.正如@EricPostpischil 在此评论中所观察到的,问题在于 clang 默认将barvar视为通用符号。 Either changing int barvar;要么改变int barvar; to int barvar = 0;int barvar = 0; , or compiling with -fno-common , fix the issue. ,或使用-fno-common编译,解决问题。

Beginning with gcc-10, gcc's default behavior is -fno-common instead of -fcommon .从 gcc-10 开始,gcc 的默认行为是-fno-common而不是-fcommon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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