是否可以仅在头文件中定义变量? [英] Is it possible to define variables in a header file only?

查看:108
本文介绍了是否可以仅在头文件中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能将我的主要cpp文件保留在程序中,而不需要所有以下内容:
int bla,bla2,bla3 = 1;
bool bla4 = false,bla5 = false;
double bla 6;
字符串名称;
char bla7;
通过将它们全部放在头文件中.这是否可能,如果可以,如果主文件需要更改变量的值,它是否能够更改,以及主文件和头文件的外观如何?顺便说一下,这些不是私有变量,它们是将由main()使用的变量.还是必须在main()中声明它们?

解决方案

您可以这样做,但为什么呢?头文件用于包含多个编译单元(源文件)使用的通用定义.应该在该单元中定义仅在单个单元中使用的项目,这些项通常在每个函数中都是本地的.头文件在其他文件中.问题是编译器会尝试创建该变量.

您可以做的是使用变量创建一个文件,并在头文件中使用外部关键字
声明这些变量. 例如:

 // 变量文件:
 int  a,b,c;
//  includefile.h 
外部  int  a,b,c; 



如果您使用外部关键字定义变量,则编译器不会创建对象,但会在其他库中查找该对象

例如:
so_drawn_variable_file.cpp

  int  a,b,c; 


so_drawn-header_file.h

 外部  int  a,b,c; 


the_other_files.cpp

 #include   "  so_drawn-header_file.h"  


I was wondering if it was possible to keep my main cpp file in a program free of all the:
int bla, bla2, bla3=1;
bool bla4=false, bla5=false;
double bla 6;
string name;
char bla7;
by putting it all in a header file. Is that possible, and if so, if the main needed to change the value of a variable, would it be able to, and how would the main and the header file end up looking? These are not private variables by the way, they are variables that would be used by main(). Or, do they have to be declared in main()?

解决方案

You could do that but why? Header files are used to contain common definitions that are used by more than one compilation unit (source file). Items used only within a single unit should be defined in that unit, generally local to each function.


if you declare a variable in a header file then it would be hard for you to include that header file in other file. the problem is compiler would try to create that variable.

What you can do is create a file with the variables and in the header file declare those variable with extern key word
as example:

//variable file:
int a, b, c;
//includefile.h
extern int a, b, c;



if you define a variable with extern key word compiler wont create object but will look for that object in other libs

example:
so_called_variable_file.cpp

int a, b, c;


so_called-header_file.h

extern int a, b, c;


the_other_files.cpp

#include "so_called-header_file.h"


这篇关于是否可以仅在头文件中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆