头文件中的变量声明 [英] Variable declaration in a header file

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

问题描述

如果我有一个变量可以在多个来源中使用 - 在标头中声明它是一种好习惯吗?还是在 .c 文件中声明它并在其他文件中使用 extern 更好?

In case I have a variable that may be used in several sources - is it a good practice to declare it in a header? or is it better to declare it in a .c file and use extern in other files?

推荐答案

你应该在头文件中声明变量:

You should declare the variable in a header file:

extern int x;

然后在一个 C文件中定义它:

int x;

在 C 中,定义和声明的区别在于定义为变量保留空间,而声明只是将变量引入符号表(并且会导致链接器在遇到链接时间).

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

这篇关于头文件中的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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