I have two cross cutting concerns in my design of my software. The memory allocator tracks memory usage in its struct(class) member variables. I also have a logger. Right now I am passing the logger and the allocator into the constructor of my objects. I can maintain a reference to them but then I would have to do that in every struct(class) I create. It would be nice if they were global but I am not sure how to do that in C. Can I construct a global memory allocator that will correctly keep track of bytes used without passing it in to my functions calls to reference?
EDIT: I am trying to use object_tracker as a global variable in my create and destroy functions. When I compile and test the files below this is the result I get: How do I use extern correctly to get the global reference to work?
gcc -I ../include object_tracker.c test_file.c test_main.c -o test
./test
/tmp/ccuT8Z1A.o: In function `Test_Create':
test_file.c:(.text+0xb): undefined reference to `object_tracker'
/tmp/ccuT8Z1A.o: In function `Test_Destroy':
test_file.c:(.text+0x4b): undefined reference to `object_tracker'
collect2: error: ld returned 1 exit status
test_file.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "object_tracker.h"
#include "test_file.h"
struct Test* Test_Create() {
struct Test* test = (struct Test*)Object_Tracker_Obj_Alloc(object_tracker, 1, sizeof(struct Test));
test->foobar = 10;
return test;
}
void Test_Destroy(struct Test* test) {
if(test != NULL) {
Object_Tracker_Obj_Free(object_tracker, test);
}
}
test_file.h
#ifndef _TEST_FILE_H_
#define _TEST_FILE_H_
#include "object_tracker.h"
extern struct Object_Tracker* object_tracker;
struct Test {
int foobar;
};
struct Test* Test_Create();
void Test_Destroy(struct Test* test);
#endif
test_main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "object_tracker.h"
#include "test_file.h"
int main(int argc, char* argv[]) {
struct Object_Tracker* object_tracker = Object_Tracker_Create();
struct Test* test = Test_Create();
Test_Destroy(test);
printf("heello\n");
}