Why can't I declare and assign a global variable in the header file, even if you use #ifndef HEADER_H

I saw some similar questions, but none of them mentioned #ifndef HEADER_H.

I have a header file and 2 C files:  constants.h  main.c  mylib.c

In constants.h :

#ifndef CONSTANTS_H
#define CONSTANTS_H

const int NUM_OF_ITEMS = 22;

#endif

In mylib.c :

#include "constants.h"
... code ...

In main.c :

#include "constants.h"

int main() {
    ... code ...
}

When I compile the command: gcc main.c mylib.c -o mainI get the following error:

/tmp/ccl55fv3.o:(.rodata+0x0): multiple definition of `NUM_OF_ITEMS'
/tmp/ccyZhu6F.o:(.rodata+0x0): first defined here
collect2: ld returned 1 exit status
  • I mentioned #ifndef, so why is this happening?
  • Is there anything other than splitting on constants.hfor an announcement and constants.cfor an appointment?
+4
source share
3 answers

- . , , , - - ( ), .

C #define . . - :

  • , static:

    static const int NUM_OF_ITEMS = 22;
    
  • extern, :

     extern const int NUM_OF_ITEMS ;
    

    constants.c:

    #include constants .h
    const int NUM_OF_ITEMS = 22;
    

1 ​​++, const C , , , , ​​ , .. "". C, , , .

+4

( .c ), , . . , #include . NUM_OF_ITEMS.

. , constants.c, NUM_OF_ITEMS, .

:

#define NUM_OF_ITEMS 22

, , .

, , static, .

+6

In C (opposite C ++), persistent objects have an external binding. Thus, both of your compilation modules will contain their own object with a name NUM_OF_ITEMS, and the linker will not know which one to use and allocate memory for it.

You can define a constant as an internal relationship, which is when the object is visible only inside the compilation unit where it is used. For this you need to use the keywordstatic

#ifndef CONSTANTS_H
#define CONSTANTS_H

static const int NUM_OF_ITEMS = 22;

#endif
+2
source

All Articles