I’m having a problem with a global file pointer in C with Visual Studio 2022 in a solution involving a large number of files that are compiled and linked using the “Build” command.
Based on the link at https://codeforwin.org/c-programming/global-variables-c#google_vignette I’ve created a file called globals.c with the code:
#include <stdio.h>
FILE* logFp;
Then in main.c I have the following code:
#include "main.h"
extern FILE* logFp;
int main(void) {
errno_t fileErr = 0;
logFp = NULL;
char logFn[FNAME_LEN] = { 0 };
printf("Type the output log filename: ");
scanf_s("%s", logFn, FNAME_LEN);
fileErr = fopen_s(&logFp, logFn, "w");
if (fileErr) {
printf("*** There is an error when attempting to open the log file ***n");
return 1;
}
int x = 5;
UINT bits = 255;
gprint(logFp, 161, "d b bn", x, bits, 2 * bits);
gprint(logFp, 1, "d b bn", x, bits, 2 * bits);
fclose(logFp);
return 0;
}
This is a test part in main() in a large solution with many other files involving the gprint() functions which I know works when logFp is defined locally.
When I attempt to compile this I get a link error that logFp is an unresolved symbol, which I get with other files in the solution containing logFp. Incidentally, main.h is my header file which includes many function prototypes, various defines and macros, as well as a number of includes. The solution works correctly until I try using a global file pointer. Some advice would be most appreciated.