How can I avoid this binding error?

if I defined a global variable (with initialization) in the header file and included this file in two files and try to compile and link, the compiler gives a binding error

headers.h:

#ifndef __HEADERS
#define __HEADERS
int x = 10;
#endif

1.c:

#include "headers.h"
main ()
{
}

2.c:

#include "headers.h"
fun () {}
0
source share
4 answers

The component complains because there will be several definitions xafter combining all the object files to create an executable file. You have two different source files, including the same header file, and this header file defines a variable xthat has a value of 10, so you get two definitions x(one in 1.c and the other in 2.c).

, (, globals.h):

#ifndef GLOBALS_H
#define GLOBALS_H

/* 
 * The "extern" keyword means that this variable is accessible everywhere
 * as long as this declaration is present before it is used. It also means
 * that the variable x may be defined in another translation unit. 
 */
extern int x;

#endif

:

#include "globals.h"

int x = 10; 
+5
  • __HEADERS ifndef.
  • , , :
// header

extern int x;

 // implementation

int x = 10;

3. 2.c .

:

// headers.h

#ifndef __HEADERS
#define __HEADERS
    extern int x;
#endif

//1.c

#include "headers.h"

int x = 10;

main ()
{
}

//2.c

#include "headers.h"
fun () {}

x . .

+1

, , ​​ ​​ .

, . - __HEADERS , , .

.

>>headers.h
    #ifndef __HEADERS
        int x = 10;
    #else
        extern int x;
    #endif

>>1.c
    #define __HEADERS
    #include "headers.h"
    int main (void) {
        return 0;
    }

>>2.c
    #include "headers"
    void fun (void) {
    }

Of course, it’s best to leave the definitions from the header files in general if you accidentally define them __HEADERSin two source files. Try:

>>headers.h
    extern int x;

>>1.c
    #include "headers.h"
    int x = 10;
    int main (void) {
        return 0;
    }

>>2.c
    #include "headers"
    void fun (void) {
    }
+1
source

#include works exactly as if you were copying and pasting text from a header file.

Think of it this way and you will see that you therefore put the line int x=10in and the source files.

The fixed version is shown below:

>>headers.h
#ifndef __HEADERS
#define__HEADERS
extern int x;  // extern tells the compiler it will be linked from another file
#endif
-----------------
>>1.c
#include "headers.h"
int x = 10;  // must have it in ONE file for linking purposes
main ()
{
}
---------------------
>>2.c
#include "headers"
fun () {}
+1
source

Source: https://habr.com/ru/post/1747166/


All Articles