user3202429
user3202429

Reputation: 117

struct use in multiple files

I have a variable (typedef struct) with hardware definitions that I need in multiple files in my project. Is there a more elegant way of doing this than using extern?

Upvotes: 0

Views: 143

Answers (2)

AndersK
AndersK

Reputation: 36082

I would suggest you declare your struct in main() and pass it to the various functions that need the struct to avoid having it as a global variable. Just have the struct in a header.

The benefits with this approach are : makes it easier to test your functions - you can pass in mock objects to simulate various states. Makes it more clear where your struct is used - only the functions that take it as an argument.

Upvotes: 2

Mohit Jain
Mohit Jain

Reputation: 30489

Something like singleton, you can implement a getInstance method.

struct BAR_ *getBarInstance(void)
{
  static struct BAR_ instance;  /* = getInitializedBar() */
  return &instance;
}

Upvotes: 1

Related Questions