C++ 在main.cpp以外的文件中包含头时链接器错误

C++ 在main.cpp以外的文件中包含头时链接器错误,c++,xcode,linker,C++,Xcode,Linker,我试图在我的代码中添加一些实用函数和全局变量,这样我就可以在项目中想要的每个类中使用它们。我希望使用.hpp文件作为定义,使用.cpp文件作为实现 这是这两个文件的摘要: // This is Utilities.hpp #ifndef utilities_hpp #define utilities_hpp namespace utils { int global_variable1; int global_variable2; void utility_fun

我试图在我的代码中添加一些实用函数和全局变量,这样我就可以在项目中想要的每个类中使用它们。我希望使用.hpp文件作为定义,使用.cpp文件作为实现

这是这两个文件的摘要:

// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp


namespace utils {

    int global_variable1;

    int global_variable2;

    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */
以及实施:

// This is Utilities.cpp
#include "Utilities.hpp"


namespace utils {

    void utility_function1(...) {
        // Some code
    }


    void utility_function2(...) {
        // Some code
    }


    void utility_function3(...) {
        // Some code
    }

}
除了我的
main.cpp
文件之外,我还有两个类。我的
main.cpp
文件包括
Class1.hpp
头,其中包括
Class2.hpp

现在我想我可以在
Class1.hpp
Class2.hpp
中添加另一个
#包括“Utilities.hpp”
,因为我在标题中使用了防护装置,所以没有任何问题。问题是,当我尝试这样做时,链接器会抛出以下错误:
Apple Mach-O链接器(ld)错误组-clang:error:linker命令失败,退出代码为1(使用-v查看调用)
,我不明白为什么或如何解决它

我正在macOS Sierra 10.12.4上使用Xcode 8.3


我希望我能够解释我的问题,非常感谢大家。标题中的全局变量缺少
extern
关键字。因此,您正在定义它们,当您在两个不同的源模块中包含头时,会产生多个定义


在头文件(
extern-int-global\u variable1;
)中添加
extern
)后,需要在.cpp文件中添加定义,在该文件中定义函数。

您违反了一个定义规则
global\u variable1
global\u variable2
应该在标题中声明
extern
,并在一个翻译单元(可能是Utilities.cpp)中定义

您已经在包含在多个转换单元中的标题中定义了全局变量,因此main.cpp中定义了一个
utils::global_variable1
,Utilities.cpp中定义了一个。当涉及到链接时间时,链接器无法知道要使用哪个
global\u variable1
,因此它会抛出一个错误

要解决此问题,请在声明中添加
extern
关键字,并在“Utilities.cpp”中添加定义:

Utilities.hpp:

// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp


namespace utils {

    extern int global_variable1;
  //^^^^^^ <-----HERE
    extern int global_variable2;
  //^^^^^^ <-----HERE
    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */
//这是Utilities.hpp
#ifndef水电站
#定义水电站的公用设施
命名空间utils{
外部整数全局变量1;

//^^^^^^它提供了更详细的输出吗?另外,尝试清理和重建您的项目。非常感谢!!!但是您能解释为什么会发生这种情况吗?我认为使用
#ifndef utilities\u hpp#define utilities\u hpp#endif
保护措施可以防止出现类似
#ifndef
的问题,包括保护措施,防止出现标题from被多次包含在一个翻译单元中。哦,你是说我的头被包含在多个
.cpp
文件中,所以我的全局变量被多次声明。我说得对吗?正确。虽然问题不是变量被多次声明,而是它们被多次定义好的,我知道了。非常感谢!
// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    int global_variable1;  //<---- Definitions added
    int global_variable2;

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }
}