Reputation: 24521
I've decided to build a modular program but I fail in implementing this in C. That's my program won't link. I believe that I fail with structuring the dependencies between my files. How is the "proper" way of doing this?
It's a bit of chicken/egg problem. I need to have struct module definied and main.c needs to be able to access module_event and event.c needs to be able to access module_main.
With this example code I get a linker error because of multiple definitions, which I can avoid with using "inline", that is however not something I want to do.
#include "main.h"
void event_cmd(void);
module module_event = {.cmd = &event_cmd};
#include "event.h"
#include "main.h"
void event_cmd(void)
{
/* */
}
typedef struct {
void (* cmd)(void)
} module;
void main_cmd(void);
module module_main = {.cmd = &main_cmd};
include "main.h"
include "event.h"
void main_cmd(void)
{
/* */
}
Upvotes: 0
Views: 143
Reputation: 34665
The problem is module_event
is defined both in event.c
and main.c
at global scope. This causes linking issue as the symbol is defined twice and linker doesn't know to which symbol it needs to link to. To resolve -
In event.h
extern module module_event;
In event.c
module module_event = {.cmd = &event_cmd};
The important thing here is the definition can either be provided in event.c
or in main.c
but not in both.
Upvotes: 2