0

I have a header error.h, and this is where I want to declare my global character array funname.

My idea is to declare funname in error.h, and include this header in all of my *.c files. funname stores the function name in which the latest error occured (in-built error + my own defined errors). Every function which has a potential to generate error assigns its name to funname like this:

//filename: someSourcecode.c

#include "error.h"

int fun1(int a, float b)
{
    strcpy(funname, "fun1");

    if(someUnexpectedEvent)
    {
        errno = MyOwnDefinedMacroWithIntegerValue;
        return -2;
    }
}

I also have error.c file which prints error messages for their respective eerno. printerror is the function in error.c which prints those error messages and that function is defined like this:

//filename: error.c

#include "error.h"

void printerror()
{
    if(errno == USERUNAVAILABLE)  //own defined errno value
    {
        fprintf(stderr, "Error:  %s   user is unavailable\n", funname);
    }

    ... //and so on
}

My Problem:

in error.h file, if I declare it like this (globally)- char funname[1024] = ""; , my invidual *.c compiles (each *.c file is compiled with command gcc -c file1.c) compiled without any error but when I tried to link them all at once (gcc file1.o file2.o file3.o file4.o main.o -o bin), it showed error like this:

/usr/bin/ld: bin/file1.o:(.bss+0x0): multiple definition of `originFuncName'; bin/main.o:(.bss+0x0): first defined here
/usr/bin/ld: bin/file2.o:(.bss+0x0): multiple definition of `originFuncName'; bin/main.o:(.bss+0x0): first defined here
/usr/bin/ld: bin/error.o:(.bss+0x0): multiple definition of `originFuncName'; bin/main.o:(.bss+0x0): first defined here
/usr/bin/ld: bin/file3.o:(.bss+0x0): multiple definition of `originFuncName'; bin/main.o:(.bss+0x0): first defined here
/usr/bin/ld: bin/file4.o:(.bss+0x0): multiple definition of `originFuncName'; bin/main.o:(.bss+0x0): first defined here

And if I declare like this (globally)- static char funname[1024] = "";, then I don't have any problem in compiling and linking, it also runs properly, except, when error message is print, the function name is not printed, probably printing null string as function name.

What should I do?

Cinverse
  • 106
  • 7

1 Answers1

1

This declaration

char funname[1024] = "";

also is a definition of the variable funname. Thus if the header is included in several translation units then you will have multiple definitions of the same variable.

You should declare the variable in the header like for example

extern char funname[1024];

and then define it in some module like

char funname[1024] = "";

As for this declaration

static char funname[1024] = "";

then the variable funname has internal linkage. It means that every translation unit where the header is included will have its own separate variable.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335