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.
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.
“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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With