3

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.

Hagai
  • 1,049
  • 11
  • 13

2 Answers2

3

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
  • 10,126
  • 9
  • 43
  • 46
  • The second, without extern, is a definition. –  Jan 10 '10 at 21:36
  • Tried that and the library cannot recognize the array. error LNK2001: unresolved external symbol _HError – Hagai Jan 10 '10 at 21:55
  • You may have special issues with your DLL file, as you hint in your question that is what you're targetting. –  Jan 10 '10 at 21:56
-1

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
  • 1,291
  • 3
  • 15
  • 22
  • 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 Jan 10 '10 at 20:46
  • 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 Jan 10 '10 at 21:21
  • That's what I did in order not to get stuck. But I still would like to know how to define a global array... – Hagai Jan 10 '10 at 21:47
  • 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 –  Jan 10 '10 at 21:52