C ++单独包含和源目录和#Include

时间:2014-09-11 07:08:46

标签: c++ build msbuild makefile project

目前在我的应用程序中我只有一个源树

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是标准做法?或者是否有其他人通常会做的事情(例如,我考虑了一个构建后步骤"导出"从主源树中列出的列出的公共标题)?

1 个答案:

答案 0 :(得分:2)

是。您只需添加新包含文件夹的路径,然后#include "filename.h"即可 另一种方法是在include路径中包含路径的相对路径。

e.g。如果您有以下目录树:

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

file.c中的任何#include都可以是相对的:

#include "Plugins/Include/pluginheader.h"  

或者您可以将./Plugins/Include添加到您的包含路径中,然后使用

#include "pluginheader.h"  

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

编辑: 这是你可以轻松尝试的事情之一,我认为这是你根据你的评论所要求的:

./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等可能有不同的行为。

然而,指定明确性更好。它更冗长,但不太容易混淆与类似命名的标题文件。

相关问题