Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.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
C++ 在库中使用未定义的extern变量with会导致macOS中的链接器错误_C++_Clang++_Macos Sierra - Fatal编程技术网

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

C++ 在库中使用未定义的extern变量with会导致macOS中的链接器错误,c++,clang++,macos-sierra,C++,Clang++,Macos Sierra,我正在创建一个动态库 foo.h 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;

我正在创建一个动态库

foo.h

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 C++14上构建得非常好,但是它在macOS clang C++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)
与我在谷歌上看到的问题最接近的链接是

我不确定答案是否在其中。

如果“myoperator”变量的“real”定义位于同一项目foo所属的另一个文件中,我认为最好放行代码

extern unsigned int myoperator;
在您的cpp文件中

如果“myoperator”变量的“real”定义位于foo所属的同一项目的另一个文件中,我认为如果您将行代码

extern unsigned int myoperator;

在您的cpp文件中

1。您需要在
foo.cpp
中定义它。2.不要使用保留的name
操作符
。它不是我使用的确切代码。在我的实际代码中,我没有使用
操作符
。感谢you@songyuanyao如果我在
foo.cpp
中定义它,那么我就不能在客户机中重新定义它。上面的代码是在LinuxGCC1中构建的。您需要在
foo.cpp
中定义它。2.不要使用保留的name
操作符
。它不是我使用的确切代码。在我的实际代码中,我没有使用
操作符
。感谢you@songyuanyao如果我在
foo.cpp
中定义它,那么我就不能在客户机中重新定义它。上面的代码是在LinuxGCC中构建的