C++结构问题

Mad*_*eer 2 c++ header multifile

所以,我是一名正在尝试学习C++的Java开发人员.C++的多文件结构对我来说很奇怪,是一个java开发人员,被类破坏了.

我正在尝试创建一个.cpp文件,可以加载其他.cpp文件,类似于Java classese加载其他类.我理解它的方式是,我有3个文件:main.cpp,filetobeloaded.h和filetobeloaded.cpp都在同一目录中.main.cpp会有一个

#include <filetobeloaded.h>
Run Code Online (Sandbox Code Playgroud)

然后filetobeloaded.h将有

#ifndef LOOP_H
#define LOOP_H

void loop_start();
void loop_run();
void loop_init();

#endif  /* LOOP_H */
Run Code Online (Sandbox Code Playgroud)

而filetobeloaded.cpp将有

void loop_init(){
    //load libraries here
}

void loop_start(){
    //this loop runs as long as the user doesn't request the program to close. 
    //In that case, this function will return and the program will exit.
}

void loop_run(){
    //render stuff here, call subroutines
}
Run Code Online (Sandbox Code Playgroud)

显然我做错了,因为我的编译器告诉我该行

#include <filetobeloaded.h>
Run Code Online (Sandbox Code Playgroud)

无效,因为该文件不存在.我已经检查过filetobeloaded.h和filetobeloaded.cpp都和main.cpp在同一个目录中.我不知道它为什么搞乱了.

问题:

1:为什么我有错误,我该如何解决?

2:有没有比我正在做的更好的方法将我的源代码分成不同的文件?

3:你能用java开发人员能理解的方式解释C++多文件结构吗?

我正在尝试使用OGL在C++中制作游戏.我正在学习c ++ vs java因为速度快,内存泄漏少(我希望)和Steam集成.

我没有一本关于c ++的好书,我在互联网上搜索过...每个人似乎都有不同的做法,这对我来说很困惑......

提前致谢!

use*_*411 8

  1. 这样做#include <...>在包括目录(编译器特定的,通常是搜索/usr/include和Linux的一帮其他的,或者在Windows编译器安装目录),而#include "..."搜索当前目录.确保使用正确的.

  2. 不,你做得对.

  3. 在C++中,有声明1和定义2.声明可以在任何地方进行,并且在单个转换单元中可以有多个与您想要的相同名称的声明,但是(非inline,非模板,非内部链接)定义最多只能在一个.cpp文件中(技术上称为"编译单元"或"翻译单元")否则您将在链接时获得"多重定义"错误.还值得注意的是,定义也可以作为声明,但不是相反.

    在C++中,在声明之前不能使用名称(函数,结构,变量等),就像在Java中一样,但是在大多数情况下,只要在使用点之上编写声明,就可以在它定义之前使用它. .

    头文件只是让你inline在所有需要它们的文件中放入声明(以及函数定义和模板定义),而不必在每个.cpp文件中反复复制和粘贴它们.你实际上可以在不使用头文件的情况下编写C++,但这将非常繁琐,并且会有大量的代码重复.

1非定义的声明示例:

extern bool bar;
class c;
int foo();
int foo();
int foo(); // Can have many declarations of the same name as long as they match
Run Code Online (Sandbox Code Playgroud)

2定义示例(也是声明):

bool bar;
bool baz = false;
class c { int m; };
int foo() { return 45; }
int foo() { return 45; } // Error: multiple definition
Run Code Online (Sandbox Code Playgroud)