在库中使用未定义的外部变量with会在macOS中导致链接器错误



我正在创建一个动态库

foo。

extern unsigned int myoperator;
int operate(int a, int b);

foo.cpp

#include "foo.h"
int operate(int a, int b){
    switch(myoperator){
    case 0:
        return a+b;
    case 1:
        return a-b;
    default:
        return a*b;
    }
}

libfoo在linux gcc c++ 14上构建得非常好,但是在macOS clangc++ 14中抛出了一个链接器错误。错误是

Undefined symbols for architecture x86_64:
  "_myoperator", referenced from:
      operate(int, int) in foo.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我在谷歌上找到的最接近这个问题的链接是https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryDesignGuidelines.html

我不确定答案是否在里面。

如果'myoperator'变量的"真正"定义是在另一个文件中,该文件是同一项目foo所属的一部分,我认为如果您将行代码

extern unsigned int myoperator;

最新更新