C++ 在C++中包含不同目录中的头文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38162070/
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-08-28 14:45:30  来源:igfitidea点击:

Include header file in different directory in c++

c++makefile

提问by J. Lin

I've been learning c++ and encountered the following question: I have a directory structure like:

我一直在学习 c++ 并遇到以下问题:我有一个目录结构,如:

 - current directory

  - Makefile

  - include

     - header.h

  - src

      - main.cpp

my header.h :

我的 header.h :

#include <iostream> 

using namespace std;

void print_hello();

my main.cpp:

我的 main.cpp:

#include "header.h"

int main(int argc, char const *argv[])
{
    print_hello();
    return 0;
}

void print_hello()
{
    cout<<"hello world"<<endl;
}

my Makefile:

我的生成文件:

CC = g++
OBJ = main.o
HEADER = include/header.h 
CFLAGS = -c -Wall 

hello: $(OBJ) 
    $(CC) $(OBJ) -o $@

main.o: src/main.cpp $(HEADER)
    $(CC) $(CFLAGS) $< -o $@

clean: 
    rm -rf *o hello

And the output of make is:

而 make 的输出是:

g++ -c -Wall src/main.cpp -o main.o src/main.cpp:1:20: fatal error: header.h: No such file or directory compilation terminated. Makefile:10: recipe for target 'main.o' failed make: *** [main.o] Error 1

g++ -c -Wall src/main.cpp -o main.o src/main.cpp:1:20: 致命错误: header.h: 没有这样的文件或目录编译终止。Makefile:10: 目标 'main.o' 的配方失败 make: *** [main.o] 错误 1

What mistakes I have made in here. It's frustrating. Really appreciate any advice!

我在这里犯了什么错误。这令人沮丧。真的很感激任何建议!

回答by Lightness Races in Orbit

You told the Makefile that include/header.hmust be present, and you told the C++ source file that it needs header.h… but you did not tell the compiler where such headers live (i.e. in the "include" directory).

你告诉 Makefileinclude/header.h必须存在,你告诉 C++ 源文件它需要header.h......但你没有告诉编译器这些头文件在哪里(即在“include”目录中)。

Do this:

做这个:

CFLAGS = -c -Wall -Iinclude

回答by abhiarora

You can either add a -Ioption to the command line to tell the compiler to look there for header files. If you have header files in include/directory, then this command should work for you.

您可以-I在命令行中添加一个选项来告诉编译器在那里查找头文件。如果include/目录中有头文件,那么这个命令应该对你有用。

gcc -Iinclude/

Since, you are using makefile, you can include this option in CFLAGSmacro in your makefile.

由于您正在使用makefile,您可以CFLAGS在 makefile 的宏中包含此选项。

CFLAGS = -Iinclude/ -c -Wall

OR

或者

You can include header files using #include "../include/header.h".

您可以使用#include "../include/header.h".

回答by daf

Perhaps change your include line:

也许更改您的包含行:

#include "include/header.h"

Assuming that's where your header exists - I'm making that assumption from your makefile

假设那是您的标头所在的位置 - 我是从您的 makefile 中做出这个假设的