bash 如何将我自己的头文件目录添加到 Mac Terminal gcc?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5697552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:48:32  来源:igfitidea点击:

How do I add my own header file directory to Mac Terminal gcc?

cmacosbashshellgcc

提问by m0rtimer

I'm trying to compile a C program (myProgram.c) that includes a custom .h file that is in a specified directory. How can I add the directory to gcc so that I can build myProgram.c anytime using just a command like gcc myProgram(with no flags and what not)

我正在尝试编译一个 C 程序 (myProgram.c),其中包含一个位于指定目录中的自定义 .h 文件。如何将目录添加到 gcc 以便我可以随时使用类似的命令构建 myProgram.c gcc myProgram没有标志和什么不是

采纳答案by Rafe Kettler

You can do this by altering the C_INCLUDE_PATHenvironment variable, e.g.

你可以通过改变C_INCLUDE_PATH环境变量来做到这一点,例如

C_INCLUDE_PATH=~/include
export C_INCLUDE_PATH

You can add that to your .bashrcor .bash_profileor whatever to always have the environment variable set properly. Here's a reference on how you can do the same for libraries and C++.

您可以将其添加到您的.bashrc.bash_profile任何内容中,以始终正确设置环境变量。这是有关如何对库和 C++ 执行相同操作的参考

回答by MrE

had to use a whole set of flags to get this working on El Capitan:

必须使用一整套标志才能在 El Capitan 上运行:

export DYLD_LIBRARY_PATH=/usr/local/include
export CPPFLAGS="-I/usr/local/include/snappy-c.h"
export CFLAGS="-I/usr/local/include/snappy-c.h"
export CXXFLAGS="-I/usr/local/include/snappy-c.h"
export LDFLAGS="-L/usr/local/lib"

回答by MrE

Makefiles would be helpful in this situation, they ease the compilation of multiple file projects.

Makefile 在这种情况下会很有帮助,它们可以简化多个文件项目的编译。

Assuming you are using these same files and they are in the same directory

假设您正在使用这些相同的文件并且它们在同一目录中

  • main.c
  • custom.c
  • custom.h
  • 主文件
  • 自定义.c
  • 自定义.h

A sample makefile could look like

示例 makefile 可能看起来像

all: main.o custom.o
    gcc main.o custom.o -o myExecutable

main.o: main.c
    gcc -c main.c

custom.o: custom.c custom.h
    gcc -c custom.c

clean:
    rm -f *.o myExecutable

Or something similar, the general format is

或者类似的东西,一般格式是

name: dependency
    command

So by running make allfrom the commandline you would be instructing the compiler to compile your source code into object files, and then link those object files together into an executable.

因此,通过make all从命令行运行,您将指示编译器将源代码编译为目标文件,然后将这些目标文件链接到一个可执行文件中。

Make should be easily available on any modern system. For more information on basic makefiles and usage refer to this simple tutorial: http://mrbook.org/tutorials/make/

Make 应该可以在任何现代系统上轻松使用。有关基本 makefile 和用法的更多信息,请参阅此简单教程:http: //mrbook.org/tutorials/make/