在C ++中的不同目录中包含头文件 [英] Include header file in different directory in c++
问题描述
我一直在学习c ++,并遇到以下问题: 我有一个类似的目录结构:
I've been learning c++ and encountered the following question: I have a directory structure like:
- current directory
- Makefile
- include
- header.h
- src
- main.cpp
我的标题.h:
#include <iostream>
using namespace std;
void print_hello();
我的main.cpp:
#include "header.h"
int main(int argc, char const *argv[])
{
print_hello();
return 0;
}
void print_hello()
{
cout<<"hello world"<<endl;
}
我的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
make的输出是:
g ++ -c -Wall src/main.cpp -o main.o src/main.cpp:1:20:致命错误:header.h:没有这样的文件或目录 编译终止. Makefile:10:目标"main.o"的配方失败 make:*** [main.o]错误1
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
我在这里犯了什么错误.真令人沮丧非常感谢任何建议!
What mistakes I have made in here. It's frustrating. Really appreciate any advice!
推荐答案
您告诉Makefile必须存在include/header.h
,并告诉C ++源文件它需要header.h
….但是您没有告诉编译器这些标头在哪里(即在"include"目录中).
You told the Makefile that include/header.h
must 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).
执行此操作:
CFLAGS = -c -Wall -Iinclude
这篇关于在C ++中的不同目录中包含头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!