我已经用C++工作了好几周了,但是头文件(或者我认为的链接器)背后的机制让我感到困惑.我已经习惯于创建一个"main.h"来分组我的其他头文件并保持main.cpp整洁,但有时这些头文件抱怨无法找到不同的头文件(即使它已声明在"main.h"中.我可能没有很好地解释它,所以这是我正在尝试做的简略版本:
//main.cpp
#include "main.h"
int main() {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
-
//main.h
#include "player.h"
#include "health.h"
#include "custvector.h"
Run Code Online (Sandbox Code Playgroud)
-
//player.h
#include "main.h"
class Player {
private:
Vector playerPos;
public:
Health playerHealth;
};
Run Code Online (Sandbox Code Playgroud)
-
//custvector.h
struct Vector {
int X;
int Y;
int Z;
};
Run Code Online (Sandbox Code Playgroud)
-
//health.h
class Health {
private:
int curHealth;
int maxHealth;
public:
int getHealth() const;
void setHealth(int inH);
void modHealth(int inHM);
};
Run Code Online (Sandbox Code Playgroud)
我不会包括health.cpp,因为它有点冗长(但确实有效),它确实有#include "health.h".
无论如何,编译器(Code :: Blocks)抱怨"player.h"找不到类型'Health'或'Vector'.我认为,如果我使用#include "main.h""player.h",它将能够找到定义Health并Vector感觉它们包含在"main.h"中.我想他们会按照自己的方式进行隧道(player.h - …
有一个函数f中foo.c,我把f Prototypes成一个头文件.
然后,有3个问题:
foo.h?foo.c和foo.h必须在同一个目录 ?f.h,foo.c并且f.h可以在不同的目录中.看一个例子:〜/的CFile/foo.c的
#include "~/hfile/f.h"
int f(void){
...
}
Run Code Online (Sandbox Code Playgroud)
〜/ HFILE/FH
int f(void);
Run Code Online (Sandbox Code Playgroud)
〜/主/ cmain.c
#include "~/hfile/f.h"
int main(void){
f();
...
}
Run Code Online (Sandbox Code Playgroud)
然后,当我f在cmain.c中调用函数时,cmain.c可以 通过指令找到fh#include,但cmain.c如何通过fh找到foo.c,因为cmain.c只包含fh 而不包含foo.c?或编译器或链接器如何通过fh找到foo.c?
这可能看起来有点愚蠢:)但它一直困扰着一段时间.当我在C++/C程序中包含一些由其他人编写的头文件时,编译器如何知道头文件中声明的类成员函数的实现在哪里?
假设我想编写一些利用OpenCV库的程序.通常我会想要使用:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
Run Code Online (Sandbox Code Playgroud)
但是,这些只是头文件,据我所知,它只声明函数但没有实现.然后编译器如何知道在哪里找到实现?特别是当我想构建一个.so文件时.
有一个类似的帖子.基本上它说第三方库,尤其是 商业产品不发布源代码,因此他们将lib文件与头文件一起发送.但是,它没有说明编译器如何知道在哪里找到lib文件.另外,那个帖子中的答案提到如果我想编译自己的代码,我需要执行这些头文件的源代码.这是否意味着我无法在没有实现源的情况下构建.so文件?