【发布时间】:2015-12-31 08:48:41
【问题描述】:
我使用包含防护的方式似乎有问题。大多数时候我的结构化工作,但在某些情况下,如下面的代码,我遇到了问题。可能导致问题的原因是我使用头文件“all.h”作为其他头文件的大集合(如“another.h”和所需的任何其他头文件)。
如果文件“another.cpp”中的代码被注释掉,代码将编译,因此在某处存在重复的函数“sleepFunc”(我认为),因为我收到以下错误:
Apple Mach-O 链接器 (Id) 错误
ld:重复符号 sleepFunc(unsigned int) in
/Users/(项目路径)/.../Another.o 和
/Users/(项目路径)/.../main.o 用于架构 x86_64
命令 /Developer/usr/bin/clang++ 失败,退出代码为 1
我在 Mac OS X Snow Leopard (10.6.8) 上使用 Xcode 4.2 版。
在写这篇文章的过程中,我发现了这个问题,就是我在“another.cpp”中包含了标题“all.h”。但是如果我做我必须做的事情(#include in "another.h",在文件 another.cpp 中使用头文件 "another.h"),这让我不开心,因为这意味着所有需要其他文件的文件都开始变得凌乱。我想为我创建的每个新文件只创建一个头文件。
(还有一个问题,为什么编译器会复制“sleepFunc”,即使有包含保护???)
是否有更好、更简洁的方式来构建包含保护和/或包含?
所有.h
#ifndef IncluderTest_all_h
#define IncluderTest_all_h
#include <iostream>
#include <stdlib.h>
#include "Another.h"
void sleepFunc(unsigned milliseconds);
#ifdef _WIN32
#include <windows.h>
void sleepFunc(unsigned milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void sleepFunc(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
#endif
#endif
main.cpp
#include "all.h"
int main (int argc, const char * argv[])
{
sleepFunc(500);
printf("Hello world!");
return 0;
}
另一个.h
#ifndef IncluderTest_another_h
#define IncluderTest_another_h
class Another{
public:
void spunky();
};
#endif
另一个.cpp
#include "all.h"
void Another::spunky(){
printf("Very spunky");
}
【问题讨论】:
标签: c++ xcode include linker-errors header-files