techsoul
techsoul

Reputation: 13

Extern variable in header file not linked properly to source file where it is defined

Problem: A variable 'VarOriginal' is defined in source C file under pragma say 'parameterX' and declared as an extern variable in a header file under the same pragma 'parameterX'. There is a process using it in which it is known that the variable is shown declared in some other header file where this variable is not present at all.

As a Workaround:I declared one more different variable 'VarNew' before the pragma 'parameterX' in the header file and similarly defined the variable 'VarNew' before the line where 'VarOriginal' was defined. And it all worked.

Header file: header_file_with_problem.h

#ifndef HEADER_FILE_WITH_PROBLEM_H

#define HEADER_FILE_WITH_PROBLEM_H

#include "ABC.h"

declare variable 'VarNew' here <------

#pragma BSS(".parameterX")

extern int VarOriginal;

#pragma BSS(DEFAULT_SECTION_BSS)

Source C File:

#define  HEADER_FILE_WITH_PROBLEM_C

#include "XYZ.h"

#include "header_file_with_problem.h"

declare variable 'VarNew' here <------

#pragma BSS(".parameterX")

int VarOriginal;

#pragma BSS(DEFAULT_SECTION_BSS)

But I am not able to understand why the problem was coming earlier. Why was the linker not able to find the definition of 'VarOriginal' in the source file and now it is able to do so, after declaring another variable before 'VarOriginal' itself?

Also, this problem is not with all source and header files present in the folder, but only a few of them.

Upvotes: 1

Views: 2030

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320747

I don't see anything defined in your source file. The

extern int VarOriginal;

is still a non-defining declaration, regardless of where you put it (source file or header file). There's not a single variable definition in your code sample, so no wonder the linker is complaining about missing definitions.

In order to define a variable in your C file you need to do either

int VarOriginal; /* no `extern` !!! */

or add an explicit initializer

extern int VarOriginal = 0; /* definition */

A mere

extern int VarOriginal; /* not a definition!!! */

that you seem to have there now (according to what you posted) is not a definition.

Upvotes: 3

Related Questions