A global variable in another library, C

I am trying to use a global variable to store 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 a program use a variable from the Utils library?

I managed to get around this problem by changing GetErr to a function that returns a string, but I'm still wondering where the error is here.

+3
source share
2 answers

You must declare it in your header file as

extern char error [];

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

char error [1024];

You select it twice

+3
source

​​:

.h:

char* GetErr();

.cpp:

char* GetErr() { return error; }

. , , .

-1

Source: https://habr.com/ru/post/1727977/


All Articles