一、多个头文件的相互调用
首先对于.h文件第一行加上(VS2019中默认如此):
#pragma once
这是为了防止头文件之间相互调用引起的一系列重定义问题,当然也可以通过宏定义来实现,比如头文件test_for_csdn.h:
#ifndef TEST_FOR_CSDN
#define TEST_FOR_CSDN
code
#endif
宏定义的TEST_FOR_CSDN为头文件名的大写,确保不会与其他变量重复。
二、多个头文件书写规范
.h文件中仅仅保留声明,在相应的.cpp文件中进行定义和初始化。这样可以防止重定义,使得代码更加简洁。注意.cpp时c++的源文件,.c文件是c的源文件,别乱搞,c++项目源文件全部用cpp格式。
三、全局变量
同样应该在.h文件中仅仅保留声明,仅仅在相应的.cpp文件中进行定义即可。比如项目中的主函数cpp文件为main.cpp,一个头文件为test.h,该头文件对应的源文件为test.cpp。
//test.h file
#pragma once
//variable
#define pi 3.14159265358979323846
extern int na;
extern char in_dir[10];
//function
in max_function(int a, int b);
//test.cpp
#include "test.h"
//define
int na;
char in_dir[10];
int max_function(int a, int b)
{
if (a>b)
return a;
else
return b;
}
//main.cpp
#include <stdio.h>
#include "test.h"
int main()
{
na=5;
in_dir="F:\\test";
max_function(2,1);
return 0;
}
在其他源文件中,只需要include “test.h”就可以使用全局变量和函数了。
Enable Ginger Cannot connect to Ginger Check your internet connectionor reload the browserDisable in this text fieldRephraseRephrase current sentence Edit in Ginger×