Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
static char passkey[PW_LENGTH];
static char passkey_mask[PW_LENGTH];
static int passkey_cursor = 0;


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
and
passkey_mask
, 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
Posted
Updated 6-Nov-18 23:24pm

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[^].
 
Share this answer
 
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:
C++
// 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;
}
 
Share this answer
 
Comments
fweinrebe 8-Sep-21 2:07am    
There's a typo in your code: extern int varArray[]; should be extern int vararray[];

Otherwise clear example. Thanks.
Richard MacCutchan 8-Sep-21 4:06am    
Well spotted, a bit late though.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900