2014-09-11 147 views
1

目前在我的应用我只是有一个单一的源代码树C++单独的Include和源目录和#INCLUDE

MyApp/Source 
|-Precompiled.hpp 
|-Precompiled.cpp 
|-Thing.hpp 
|-Thing.cpp 
|-Main.cpp 
|-Component 
| |-ComponentThing.hpp 
| |-ComponentThing.cpp 
| |-... 
|-ComponentB 
| |-ComponentBThing.hpp 
| |-... 
|-PluginCandiate 
| |-PluginThing.hpp 
| |-PluginThing.cpp 
| |-... 
... 

但是我希望做一个插件系统(这样少的东西是与核心应用程序的一部分清晰的边界),我想移动到单独的Include \ MyApp树中的那么多.hpp文件。所以新的树可能看起来像:

MyApp/Include/MyApp 
|-Thing.hpp 
|-Component 
| |-ComponentThing.hpp 
| ... 
|-ComponentB 
| |-ComponentBThing.hpp 

MyApp/Source 
|-Precompiled.hpp 
|-Precompiled.cpp 
|-PrivateThing.hpp 
|-PrivateThing.cpp 
|-Component 
| |-ComponentThing.cpp 
| |-... 
|-ComponentB 
| |-... 
... 

Plugins/PluginCandiate/Source 
|-PluginThing.hpp 
|-PluginThing.cpp 
... 

现在用目前的方式,我只包含我的包含路径上的“源”。这意味着,例如在ComponentThing.cpp我可以做说:

#include "Precompiled.hpp" 
#include "ComponentThing.hpp" 
#include "ComponentOtherThing.hpp" 
#include "ComponentB/ComponentBThing.hpp" 

由于当前目录永远是第一位的包括路径上。但是,如果我拆分我的公共包含目录和源目录,情况就不再这样了。我可以将Include/Myapp /放在包含路径中,但是Id仍然需要全部组件路径。

是否有一种简单的方法可以避免这种情况(使用MSVC MSBuild和Linux make文件),还是只有完整的#includes才是标准做法?或者有其他人通常会做的事情(例如,我考虑了构建后步骤来“导出”主源树中列出的公共标题集)?

+0

您能否详细说明您的意思:“我可以将Include/Myapp /放在包含路径中,但是Id仍然需要全部组件路径”? – downhillFromHere 2014-09-11 07:54:51

+0

因此,对于说ComponentThing.cpp我不需要一些包括像“../../Include/MyApp/Component/ComponentThing.hpp”的垃圾,但我仍然需要“组件/ ComponentThing.hpp”,而不是只是“ ComponentThing.hpp“ – 2014-09-11 09:29:22

回答

2

是的。您可以将路径添加到新的包含文件夹,只需要将路径中的相对路径包含在包含路径中即可。#include "filename.h"

例如如果你有以下目录树:

+ MyApp 
    - file.c 
    - file.h 
    + Plugins 
    + Include 
    - pluginheader.h 

在file.c任何#include可能是相对的:

#include "Plugins/Include/pluginheader.h" 

,或者你可以添加./Plugins/Include到include路径,只需使用

#include "pluginheader.h" 

(您不必指定完整路径,只是工作目录的相对路径)

编辑: 这是那些东西,你可以easilly尝试自己一个,我觉得这是一个基于您的评论你问的是什么:

./file.c

#include <stdio.h> 
#include "module/function.h" 
int main() 
{ 
    int sum; 
    myStruct orange; 
    myStruct_insert(&orange, 5, 6); 
    sum = myStruct_sum(&orange); 
    printf("%d",sum); 
    return 0; 
} 

./module/function.h

typedef struct{ 
    int one; 
    int two; 
}myStruct; 

void myStruct_insert(myStruct *apple, int one, int two); 

int myStruct_sum(myStruct *apple); 

./module/function.c

#include "function.h" 
void myStruct_insert(myStruct *apple, int one, int two) 
{ 
    (*apple).one = one; 
    (*apple).two = two; 
} 

int myStruct_sum(myStruct *apple) 
{ 
    return (*apple).one+(*apple).two; 
} 

我编译了这个gcc file.c ./module/function.c(不包括路径添加)。它编译没有错误和正确执行:

$ gcc file1.c module/function.c 
$ ./a 
11 
$ 

所以回答你的问题是肯定的,它将包括在同一文件夹标头,你的代码编译器目前正在对。或者至少对于GCC来说。 MSVC等可能有不同的行为。

但是最好指定明确性。它比较冗长,但不太容易与名称类似的头文件混淆。

+0

当然,但假设每个模块只有一个平面目录,这不是我所说的,我也在讨论包括东西在内的东西,而不是跨组件/模块包含哪里ModuleX/ComponentX/ThingX.hpp是有道理的,虽然没有那么讨厌/包括/) – 2014-09-11 09:37:02

+0

@FireLancer增加了一个工作的例子,我认为更好地捕捉你的问题。 – Baldrickk 2014-09-11 10:12:25