Home > Software engineering >  "multiple definition of" while variable is not defined anywhere else in the scope
"multiple definition of" while variable is not defined anywhere else in the scope

Time:05-23

I have these three source files:

test.h

#ifndef __TESTH
#define __TESTH

    #ifdef __cplusplus
        #define EXTERNC extern "C"
    #else
        #define EXTERNC
    #endif

    typedef struct {
        uint8_t value;
    } my_struct;
    
    EXTERNC void initialise();
    EXTERNC void load(my_struct**);

#endif

test.cpp:

#include <cstdint>
#include "test.h"

my_struct test;

void initialise() {
    test.value = 200;
}

void load(my_struct** struct_ptr) {
    *struct_ptr = &test;
}

main.cpp:

#include <cstdint>
#include <iostream>
#include "test.h"

my_struct *test;

int main() {
    initialise();
    load(&test);
    
    while (true) {
        std::cout << test->value << std::endl;
    }
}

When I compile it, the linker gives me an error telling me that test has been defined multiple times (first defined in test.cpp).

Why? To me it seems like it doesn't leave the scope of test.cpp.

And when I remove the definition of test in main.cpp, it gives me an undefined error!

Thank you for taking the time out of your day to help me.

CodePudding user response:

I think you would need to scope test.cpp's test variable to that file only, assuming your test pointer in main.cpp is different than test in test.cpp

namespace {
    my_struct test;
}

See here

  •  Tags:  
  • c
  • Related