头文件中的多个目录:最佳实践 [英] Header Files in Multiple Directories: Best Practices

查看:174
本文介绍了头文件中的多个目录:最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的很多动态语言(JavaScript的,蟒蛇,哈斯克尔等),code,但现在我正在学习C读研,我不知道我在做什么。

I write lots of code in dynamic languages (javascript, python, haskell, etc.), but I'm now learning C for graduate school and I have no idea what I'm doing.

本来我是用一个makefile,这已工作相当好建设我的所有源在一个目录。然而,我的项目越来越多,我想分裂源成多个目录(单元测试,utils的,核心的,等等)。例如,我的目录树看起来像下面这样:

Originally I was building all my source in one directory using a makefile, which has worked rather well. However, my project is growing and I would like to split the source into multiple directories (unit tests, utils, core, etc.). For example, my directory tree might look like the following:

.
|-- src
|   |-- foo.c
|   |-- foo.h
|   `-- main.c
`-- test
    `-- test_foo.c

测试/ test_foo.c 同时使用的src / foo.c的的src / foo.h中。使用的makefile,什么是建立这个最佳/标准的方式? preferably,就建设项目的一个规则,一个用于构建测试。

test/test_foo.c uses both src/foo.c and src/foo.h. Using makefiles, what is the best/standard way to build this? Preferably, there would be one rule for building the project and one for building the tests.

我知道有这样做,包括autoconf和其他自动解决方案的其他方式。不过,我想明白发生了什么,并能够从头开始写Makefile的,尽管它可能不切实际。

I know that there are other ways of doing this, including autoconf and other automatic solutions. However, I would like to understand what is happening and be able to write the makefiles from scratch despite its possible impracticality.

任何指导或提示将AP preciated。谢谢!

Any guidance or tips would be appreciated. Thanks!

所以给出的三种解决方案至今如下:

So the three solutions given so far are as follows:


  • 将全球使用在一个平行的头文件包含目录

  • 使用在的#include 语句路径为的#include../src/foo.h\"

  • 使用 -I 开关告知地点包括编译器

  • Place globally used header files in a parallel include directory
  • use the path in the #include satement as in #include "../src/foo.h"
  • use the -I switch to inform the compiler of include locations

到目前为止,我喜欢 -I 开关解决方案,因为它不涉及改变源$ C ​​$ C时,目录结构的变化。

So far I like the -I switch solution because it doesn't involve changing source code when directory structure changes.

推荐答案

有关test_foo.c你只需要告诉所在的头文件可以找到的编译器。例如。

For test_foo.c you simply need to tell the compiler where the header files can be found. E.g.

gcc -I../src -c test_foo.c

那么编译器也将寻找到这个目录下找到头文件。在test_foo.c你写的话:

Then the compiler will also look into this directory to find the header files. In test_foo.c you write then:

#include "foo.h"

修改
要链接对foo.c的,其实对foo.o的,你需要提到它在目标文件列表。我假设你已经将目标文件,在那之后做的:

EDIT: To link against foo.c, actually against foo.o, you need to mention it in the object file list. I assume you have already the object files, then do after that:

gcc test_foo.o ../src/foo.o -o test

这篇关于头文件中的多个目录:最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆