简体   繁体   English

在 C++ 中包含头文件

[英]Including header files in C++

I'm very new to C++ and I've just figured out that main() is meant to call all the header functions.我对 C++ 很陌生,我刚刚发现 main() 是为了调用所有的头函数。

I've made 5 header files, all .hpp, and placed them in the header folder of my project.我制作了 5 个头文件,都是 .hpp,并将它们放在我的项目的头文件夹中。 As you can see they all have the same extension and location:如您所见,它们都具有相同的扩展名和位置:

在此处输入图片说明

But when I call the header files in my main.cpp file... only getline_demo.hpp can be found by the system:但是当我调用main.cpp文件中的头文件时……系统只能找到getline_demo.hpp:

在此处输入图片说明

The error is "cannot open filename.hpp" for the others.其他人的错误是“无法打开文件名.hpp”。

What could be happening and how could I fix it?可能会发生什么,我该如何解决?

There are multiple ways to solve this:有多种方法可以解决这个问题:

1) Easiest: just put the fullpath from disk 1)最简单:只需从磁盘中放置完整路径

#include "C:\... "

2) Inside the properties of the project C/C++ -> General -> Additional Include Directories the full path to the folder containing the files 2) 在项目 C/C++ -> General -> Additional Include Directories 的属性中,包含文件的文件夹的完整路径

2') You can use macros that specifies the project dir, solution dir ... 2') 您可以使用指定项目目录、解决方案目录的宏...

The main() function is not meant to "call all the header functions" . main()函数并不是要“调用所有的头函数”

You don't have any error here (assuming your files are in the same folder which seems to be the case here).你在这里没有任何错误(假设你的文件在同一个文件夹中,这似乎是这里的情况)。
You are using the Visual Studio Code's editor.您正在使用 Visual Studio Code 的编辑器。 It seems that your editor is misconfigured and could not find the files in its own file tree representation, that's all.您的编辑器似乎配置错​​误,无法在其自己的文件树表示中找到文件,仅此而已。


EDIT:编辑:

If you have an include error at compilation, then this is that you missed to specify the paths correctly.如果您在编译时遇到包含错误,那么这是您错过了正确指定路径的原因。 For example, if you have the "main.cpp" alongside an "include" folder that contains your .hpp files, you will have to include the one you want this way:例如,如果您在包含 .hpp 文件的“include”文件夹旁边有“main.cpp”,则必须以这种方式包含您想要的:

#include "include/my_header.hpp"

Always give relative paths .总是给出相对路径

From your screenshot it looks like getline_demo.hpp can be fond by your IDE, check using your file explorer where the files are placed and move the others into the same folder.从您的屏幕截图看来,您的 IDE 可能喜欢getline_demo.hpp ,请使用您的文件资源管理器检查放置文件的位置并将其他文件移动到同一文件夹中。

Never use absolute paths in your project/source files unless you want to cause problems for yourself and others in the future!不要在你的项目/源文件中使用绝对路径,除非你以后想给自己和他人造成问题!

Also remember that the views IDEs give you of your project may not correlate to the layout on the filesystem - which is the layout your compiler cares about!还要记住,IDE 为您提供的项目视图可能与文件系统上的布局无关——这是您的编译器关心的布局!

Special thanks go to Microsoft Visual Studio for the "helpful" filters it creates.特别感谢 Microsoft Visual Studio 为其创建的“有用”过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM