第一个带有标题和2个.cpp文件的程序

时间:2014-07-14 21:06:10

标签: c++ visual-c++ c++11

我正在编写一个程序,我需要两个不同的.cpp文件,第一个是我的主文件,第二个文件是主要使用的几个函数。我是否还需要头文件进行初始化?不太确定如何去#includes ..任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

如果您想使用多个.cpp个文件 -

  • .h文件基本上用于将.cpp个文件链接在一起。
  • 您可以将函数声明放在.h文件中。
  • 您可以将.h文件包含在主.cpp文件中。
  • 您可以在函数.cpp文件中编写函数,并包含.h文件。

请查看此链接以获取更多信息 - Multiple .cpp file programs

答案 1 :(得分:0)

这应该适合你。

您的main.cpp文件:

// main.cpp
#include "header.h" // bring in the declarations

// some function that performs initialization.
// it is static so it cannot be seen outside of this compilation unit.
static void init_function() {

}

// initialization functions etc. here
int main(int argc, char *argv[]) {

  return 0;
}

您的header.h文件:

// header.h
#ifndef HEADER_H_INCLUDED_
#define HEADER_H_INCLUDED_
// this is an include guard, google the term

// function declaration
int my_function();


#endif /* HEADER_H_INCLUDED_ */

您的header.cpp文件:

// header.cpp 
//
// file containing the definitions for declarations in header.h
#include "header.h"

// definition of my_function
int my_function() {
// do cool stuff
}

// some helper function that is not to be used outside of
// header.cpp
static int helper_function() {

}

只有要向其他编译单元公开的函数和类才需要头文件。我假设您不希望将初始化函数公开给任何其他模块,因此可以不在头文件中声明它们。它们也应标记为static,因此它们没有外部链接。

在C ++中,您也可以使用匿名命名空间来提供内部链接,但现在这不应该关注您。

相关问题