How to extern a structure variable to share it between multiple source files

Summary

The issue arises from the incorrect use of the extern keyword when sharing a structure variable between multiple source files. The extern keyword is used to declare a variable that is defined elsewhere, but in this case, the variable is defined in the header file, causing a multiple definition error.

Root Cause

The root cause of the issue is:

  • The extern keyword is used to declare the myQueue variable in the header file, but it is also defined in the same header file.
  • The myQueue variable is then initialized in the main.c file, which causes a multiple definition error when the header file is included in other source files.

Why This Happens in Real Systems

This issue can occur in real systems when:

  • Global variables are used to share data between multiple source files.
  • Header files are used to declare variables and functions that are used by multiple source files.
  • Multiple definitions of the same variable occur, causing the linker to fail.

Real-World Impact

The impact of this issue can be:

  • Linker errors, such as undefined reference or multiple definition errors.
  • System crashes or unexpected behavior due to incorrect data sharing between source files.
  • Difficulty in debugging due to the complexity of the issue.

Example or Code

// queue.h
#ifndef QUEUE_H
#define QUEUE_H

struct queue_type {
    int front; // read index
    int rear; // write index
    int buffer[BUF_LEN];
    SPI_STATE spi_state; // SPI status flag
};

// Declare the global queue variable
extern struct queue_type myQueue;

#endif // QUEUE_H
// main.c
#include "queue.h"

// Define and initialize the global queue variable
struct queue_type myQueue;
myQueue.front = 0; // start read index at 0
myQueue.rear = 0; // start write index at 0
memset(myQueue.buffer, 0, BUF_LEN * sizeof(int)); // initialize all buffer elements to 0
myQueue.spi_state = SPI_NOT_READY; // initial SPI state

How Senior Engineers Fix It

Senior engineers fix this issue by:

  • Declaring the global variable in the header file using the extern keyword.
  • Defining the global variable in a single source file, such as main.c.
  • Including the header file in all source files that need to access the global variable.

Why Juniors Miss It

Juniors may miss this issue because:

  • Lack of understanding of the extern keyword and its purpose.
  • Insufficient experience with global variables and header files.
  • Failure to recognize the multiple definition error and its causes.

Leave a Comment