How to declare a pointer with extern in C?
I am writing a C software for a microcontroller, the compiler is Microchip MCC18.
For test purposes, I have written a very simple program as follow:
.c file
#include "x.h"
char *now开发者_开发问答_clock;
.h file
extern char *now_clock;
With the above code I get a syntax error, but I don't know what is wrong. Any help?
The code shown, which doesn't seem to have changed across the edit, compiles correctly for me on MacOS X 10.6.6 with GCC 4.5.2 under stringent warnings - as indeed it should do.
$ cat x.h
extern char *now_clock;
$ cat x.c
#include "x.h"
char *now_clock;
$ gcc -O -std=c99 -Wall -Wextra -pedantic -c x.c
$
The code in x.c shows correct style - it includes the header that declares the variable to cross-check the definition of the variable. You can also add an initializer to the definition in x.c without problems.
I conclude that you have over-simplified your example and lost the problem in the process.
You don't declare extern char* now_clock
in the .c file which is what you are doing by including x.h in your .c. Remove #include "x.h"
and you'll be fine.
Only include x.h in the .c files that want to access the variable.
精彩评论