如何在.h文件中声明静态变量并在.c文件中定义它? [英] How to declare a static variable in .h file and define it in a .c file ?

查看:294
本文介绍了如何在.h文件中声明静态变量并在.c文件中定义它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在c中构建一个代码库,使用atmega微控制器驱动键盘,

因为我创建了2个文件keypad.h和键盘.c



我正在使用GCC C编译器



当我尝试声明一个静态变量时。 h文件然后在.c文件中定义,如下;

.h文件

Hello everyone,
I am building a code library in c to drive a keypad using atmega microcontroller,
for that i have created 2 files keypad.h and keypad.c

I am using GCC C compiler

when i try to declare a static variable in .h file and then define it in .c file, as follow;
.h file

static char passkey[];		
static char passkey_mask[];
static int passkey_cursor;





.c file



.c file

static char passkey[PW_LENGTH];
static char passkey_mask[PW_LENGTH];
static int passkey_cursor = 0;





编译器理解有2个具有相同名称的passkey_cursor变量并给我一个警告.h文件中的那个已定义但从未使用



但是对于数组



the compiler understand that there is 2 passkey_cursor variables with the same name and give me a warning that the one in the .h file is defined but never used

but for the arrays

passkey

passkey_mask

,一切正常。



我需要你的支持,

谢谢提前,

z3ngew



我的尝试:



如果我从头文件中删除这一行



, everything is working fine.

Kindly i need your support,
Thanks in advance,
z3ngew

What I have tried:

if i remove this line from header file

static int passkey_cursor;





一切都很好,但变量未在头文件中声明,因为我打算做



everything is fine, however the variable is not declared in the header file as i am intending to do

推荐答案

您应该在标头中声明变量 extern 并在源文件中定义它(不包含 static keywork: static 在源文件中提供内部链接)。例如,请参阅: C中的静态关键字的内部链接 - Stack Overflow [ ^ ]。
You should declare your variable extern in the header and define it in the source file (without the static keywork: static in source file provides internal linkage). See, for instance: Internal linkage with static keyword in C - Stack Overflow[^].


如果它们是静态的,只是在.cpp文件中,你不应该在头文件中定义它们。如果您正在尝试创建全局变量,那么您应该在标头中声明它们 extern ,并仅在一个 .cpp文件中为它们赋值,喜欢:

You should not be defining them in the header file if they are static, just in the .cpp file. If you are trying to create global variables then you should declare them extern in the header, and give them a value in one .cpp file only, like:
// header.h
extern int variable;
extern int varArray[];

// main.cpp
#include "header.h"
int variable = 0;
int vararry[22];

// sub.cpp
#include "header.h"

void sub()
{
    variable = 55;
    vararry[0] = 10;
}


这篇关于如何在.h文件中声明静态变量并在.c文件中定义它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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