-1

I've read a lot for this problem ,but I haven't found a proper solution. So i have 4 files:

includes.h - which contains all libraries I need in other files + some global functions
cities.h - which contains declarations of  2 classes
cities.cpp - which contains definitions of the 2 classes in cities.h
source.cpp - where is the main functon

And I have(and need) these includes

//cities.h
#include "includes.h"

//cities.cpp
#include "cities.h"

//source.cpp
#include "cities.h"

I've tried almost all combinations of #ifndef in all of the files and the program continues to give me the same error: function_X already declared in cities.obj.And this error repeats for all functions in "includes.h". Please help me.This makes me a lot of headaches.

4

2 回答 2

0

除了@sftrabbit 所说的之外,如果您正在制作一个仅需要在头文件中定义函数的标头库,则可以使用关键字inline.

// includes.h
inline void foo() {
    // implementation
}

inline int bar(int x) {
    // implementation
}

不要将这种用法inline与它作为inline函数调用的编译器建议的其他用途相混淆。

于 2013-05-14T14:00:26.340 回答
0

正如您在评论中所描述的,您的includes.h头文件中有函数定义。当它包含在多个实现文件中时,您最终会在程序中对这些函数进行多个定义。这打破了单一定义规则。您应该简单地声明函数includes.h并将它们的定义移动到includes.cpp文件中。

像这样的东西:

// includes.h

void foo();
int bar(int);


// includes.cpp

void foo() {
  // implementation
}

int bar(int x) {
  // implementation
}

我将尝试抢占通常遵循此答案的问题。不,您的包含警卫 ( #ifndef ...) 并不是为了防止这种情况发生。它们仅防止标题在单个翻译单元中多次包含。您将标题包含在多个翻译单元中,包含保护不会停止。

于 2013-05-13T21:46:49.483 回答