簡體   English   中英

鏈接到包含全局變量的靜態庫時,clang 和 gcc-10 之間的不同行為

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

我有一個靜態鏈接庫,其中包含一個全局變量barvar 我可以使用 gcc-10 或 clang(這是在 macOS Catalina 上)毫無問題地編譯庫。 有趣的是,當我嘗試將其鏈接到使用該庫的程序時,兩者的行為有所不同。 這是代碼:

globvars.h ,聲明了int barvar

#ifndef H_GLOBVARS_H                              
#define H_GLOBVARS_H                             
  
extern int barvar;                              

#endif  

globvars.c ,定義了int barvar

#include "globvars.h" 
int barvar;

foo.c ,函數foo設置並打印barvar

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

這是test.c ,使用庫的程序:

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

當我用 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

當我用 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

有錯誤:

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

有任何想法嗎? 有趣的是,似乎必須與GCC-10編譯完成的唯一步驟globvars.c 我可以在所有其他步驟中使用 clang 和 clang 鏈接器,一切都很好。 clang 是否有可能優化掉globvars.c所有變量? 我怎樣才能防止這種情況?

正如@EricPostpischil 在此評論中所觀察到的,問題在於 clang 默認將barvar視為通用符號。 要么改變int barvar; int barvar = 0; ,或使用-fno-common編譯,解決問題。

從 gcc-10 開始,gcc 的默認行為是-fno-common而不是-fcommon

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM