Home > Mobile >  How to use static variable defined at the *.c file end
How to use static variable defined at the *.c file end

Time:08-18

We all know that static functions defined after main needs to have function header at the top because compiler will complain about non existing function. I have big static array at the *.c file end and I do not want to move it to the top. How do I tell compiler that this static variable exists at the bottom of the file? because currently it can not see it.

At the end of my c file:

static const unsigned char bitmap[] =
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,...

CodePudding user response:

You can first declare bitmap without defining it:

static const unsigned char bitmap[];

and later define it:

static const unsigned char bitmap[] =
    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,… };

Clang accepts this, but GCC does not, apparently because it violates C 2018 6.9.2 3:

If the declaration of an identifier for an object is a tentative definition and has internal linkage, the declared type shall not be an incomplete type.

To fix that, you need to give the size at the first declaration:

static const unsigned char bitmap[256];

I do not see a technical reason for that, though; a compiler should not need to know the size of an array whose identifier has internal linkage anymore than it needs to know the size of an array whose identifier has external linkage, as long as it is fully defined by the end of the translation unit. (Unless it was to allow for single-pass assemblers that could not do forward symbol resolution except by creating an external identifier and letting the linker do it. But then how do they resolve forward-declared functions?)

CodePudding user response:

Declaring the array static means its presence will only be known to the particular compilation unit in which it is defined. As @Eric wrote (and you know about forward declarations) you could continue to work with the array in main.c.

An alternative to achieve the same effect would be to put the definition of the array (without static into its own "pure data" '.c' file. Then use extern in main.c to gain visibility of that array. No other source files will know it exists.

In this way, you will have another object file to link, but its text will only be (re-) compiled when you edit that file. main.c can get about its business with code (and be smaller and lighter as a benefit).

bitmap.c

const unsigned char bitmap[] =
    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,… };

main.c

extern const unsigned char bitmap[];

funcs.c

// Huh? What? is there an array somewhere I don't know about???
  • Related