Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an array of strings of characters in header file?

Tags:

I have many different 3 axis sensors I am writing test code for. In the C files for each of them, I have the same char string defined:

char axis[3][8] = {"X", "Y", "Z"}

which I use when I "for" loop results to print the axis that is failing like this:

DEVICETEST_LOG("%s Failed %s axis for Min range\n",device_name[DUT], axis[i]);

I was thinking to save some space I could define a character string array in a header file to use all over the place.

I have tried a number of things, but I can't seem to get an array of strings defined in my header file that I can iterate through to pass a compile.

like image 419
user1054210 Avatar asked Feb 08 '12 15:02

user1054210


People also ask

Can we define an array in header file?

int array[4] = {1,2,3,4}; will work, but putting objects in headers is generally a bad idea because it is easy to accidentally define the object multiple times just by including the header more than once. Inclusion guards are only a partial fix for that problem.

How do you define an array of characters?

“array_name = new char[array_length]” is the syntax to be followed. Anyways we can do both declaration and initialization in a single by using “char array_name[] = new char[array_length]” syntax. The length of the array should be declared at the time of initialization in a char array.

How do you declare a character array in C?

char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a '\0' (null) byte. The null byte is required as a terminating byte when string is read as a whole.


1 Answers

If you must put it in a header file, use extern or static:

// option 1
// .h
extern char axis[3][8];

// .c
char axis[3][8] = { "X", "Y", "Z" };

// option 2
// .h
static char axis[3][8] = { "X", "Y", "Z" };

Extern tells the linker that there is a global variable named axis defined in one of our implementation files (i.e. in one .c file), and I need to reference that here.

static, on the other hand, tells the compiler the opposite: I need to be able to see and use this variable, but don't export it to the linker, so it can't be referenced by extern or cause naming conflicts.

like image 197
Richard J. Ross III Avatar answered Oct 16 '22 07:10

Richard J. Ross III