I have a file, file1.c, where I would like to define some constants if some requirements are met, to be used in an other file, file3.c.
file1.c:
#include "header.h"
int set_constants(void) {
#ifdef EXAMPLE_MACRO
int fd, status, size;
fd = open(EXAMPLE_DRIVER, RD_ONLY);
ioctl(fd, EXAMPLE_IOCTL_CHECK_SIZE, &size);
if (size == SIZE_CONDITION) {
/* Here i would like to define the constants
A, B, and C. */
} else {
/* Here I would like to define the constants
A, B, and C to something else than above. */
}
return 0;
#endif
/* If EXAMPLE_MACRO is not defined, I would like to set
A, B and C to something else. */
return 0;
The function, set_constants(), would be called from an init function in file2.c, which makes a call to a function in file3.c that uses the constant A:
#include "header.h"
void file2_init(void) {
set_constants();
file3_function();
}
In file3.c, I would like to create a global array with A elements:
#include "header.h"
uint8_t array[A];
void file3_function(void)
{
/* Do something with array */
}
I understand that A, B and C can not be defined as macros, since the variable size is not known when the macros are processed by the pre-processor. Would such constants even be possible to create (using the language C)?
I've tried to define A, B, and C as global integer variables (I know they are not constant, but it is my only idea so far) in file1.c, and declared them like this in a header file header.h:
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H
extern int A;
extern int B;
extern int C;
void set_constants(void);
void file3_function(void);
#endif _MY_HEADER_H_
But then I get the error:
error: variably modified 'array' at file scope
array[A] needs to be at global scope, my question is, how do i declare and define A, B, and C such that they are visible to file3.c, and do not rise the error above?
I've also tried to make A, B, and C to const int, like so;
#include "header.h"
int set_constants(void) {
#ifdef EXAMPLE_MACRO
int fd, status, size;
fd = open(EXAMPLE_DRIVER, RD_ONLY);
ioctl(fd, EXAMPLE_IOCTL_CHECK_SIZE, &size);
if (size == SIZE_CONDITION) {
const int A = 1;
const int B = 1;
const int C = 1;
} else {
const int A = 2;
const int B = 2;
const int C = 2;
}
return 0;
#endif
const int A = 3;
const int B = 3;
const int C = 3;
return 0;
and declared A, B, and C to extern const int in header.h:
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H
extern const int A;
extern const int B;
extern const int C;
void set_constants(void);
void file3_function(void);
#endif _MY_HEADER_H_
But then I get the compile error:
error: declaration of 'A' shadows a global declaration [-Werror=shadow] const int A = 1;
In file included from file1.c: header.h: error: shadowed declaration is here [-Werror=shadow] extern const int A;