我似乎对使用包含警卫的方式做错了。大部分时间我的结构都有效,但在某些情况下,如下面的代码,我有问题。可能导致问题的是我使用头文件" all.h"作为其他头文件的大集合(例如" another.h"以及所需的任何其他头文件)。
如果文件" another.cpp"中的代码将编译代码。被注释掉了,所以在某个地方有一个重复的函数" sleepFunc" (我认为),因为我收到以下错误:
Apple Mach-O链接器(Id)错误
ld:
中的重复符号sleepFunc(unsigned int)/ Users /(项目路径)/.../ Another.o和
架构x86_64的/ Users /(项目路径)/.../ main.o
Command / Developer / usr / bin / clang ++以退出代码1
失败
我在Mac OS X Snow Leopard(10.6.8)上使用Xcode 4.2版。
在这篇文章的打字过程中,我发现了这个问题,包括标题" all.h" in" another.cpp"。但是,如果我做了我必须做的事情(#include在" another.h",使用标题" another.h"在文件another.cpp中),它让我不高兴,因为这意味着所有需要其他文件的文件开始变得混乱。我想为我制作的每个新文件只有一个头文件。
(还有一个问题,为什么编译器会复制" sleepFunc",即使使用包含警卫???)
是否有更好,更干净的方法来构建包含警戒和/或包含?
#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
#include "all.h"
int main (int argc, const char * argv[])
{
sleepFunc(500);
printf("Hello world!");
return 0;
}
#ifndef IncluderTest_another_h
#define IncluderTest_another_h
class Another{
public:
void spunky();
};
#endif
#include "all.h"
void Another::spunky(){
printf("Very spunky");
}
答案 0 :(得分:0)
因为在两个cpp文件中包含all.h,所以重复了Symbol。尝试将sleep的实现放入第三个cpp文件或对函数使用static void。对于我所看到的内容,包括警卫是可以的。