tags:

views:

106

answers:

2

I am trying a global variable to hold my error message in C.

One library called Utils has:

#ifndef private_error_h
#define private_error_h

extern char error[1024];

__declspec(dllexport) void FillError(char* newError);
#define GetErr() error

#endif

File error.c:

#include "private_error.h"

char error[1024];
void FillError(char* newError) {
  // ...
}

Then I try to use it in a program:

#include "private_error.h"

int main() {
  FillError("General error");
  printf("%s\n", GetErr());
  return 0;
} 

It creates two variables with different addresses. How can I make the program use the variable from the Utils library?

I did manage to bypass this problem by changing GetErr to a function returning the string, but I am still wondering where the error is here.

+3  A: 

You have to declare it in your header file as

extern char error[];

and in your code file (.c file) , declare it

char error[1024];

You are allocating it twice

Larry Watanabe
The second, without extern, is a definition.
Roger Pate
Tried that and the library cannot recognize the array.error LNK2001: unresolved external symbol _HError
Gray Raven
You may have special issues with your DLL file, as you hint in your question that is what you're targetting.
Roger Pate
A: 

Why not use function like this:

in .h:

char* GetErr();

and in .cpp:

char* GetErr() { return error; }

Try to avoid global variables. In file scope its pretty safe, but if you try to use it trough many files it can cause big errors.

qba
What's wrong with a global array? How will having a "get" function prevent 'big errors' if many files use it? They still have access to the array.
Pod
They have if they explicitly declare to use it. You avoid for example names errors while `error` is rather popular name for variable:P Hiding implementation is always a good practice.
qba
That's what I did in order not to get stuck. But I still would like to know how to define a global array...
Gray Raven
Gray: The solution is to *declare* it in the header and *define* it in the implementation (.c) file, as Larry's answer almost says exactly. Also see the declaration/definition examples at http://stackoverflow.com/questions/2037880/how-can-i-avoid-including-class-implementation-files/2038233#2038233
Roger Pate