i new concept of extern. today @ work came across large number of extern functions declared inside of header file; foo.h. somewhere off in mess of folders found foo.c file contained definition of said functions did not #include foo.h. when got home decided play around extern storage class examples. after doing reading in "c book" came with.
here did not expect work. did.
main.c
#include <stdio.h> int data; int main() { data = 6; printf("%d\n", getdata()); data = 8; printf("%d\n", getdata()); return 0; } externs.c
int getdata() { extern int data; return data; } bash
gcc main.c externs.c -o externs i didn't think work because function not technically (or @ least verbose) defined before main. work because default storage class int getdata() extern? if so, why bother following example (similar saw @ work)?
main2.c
#include <stdio.h> #include "externs.h" int data; int main() { data = 6; printf("%d\n", getdata()); data = 8; printf("%d\n", getdata()); return 0; } externs.h
#ifndef _externsh_ #define _externsh_ extern int getdata(); #endif externs.c
int getdata() { extern int data; return data; } bash
gcc main2.c externs.c -o externs
functions implicitly extern. can change declaring them static.
you right redundant extern int getdata(); compared int getdata(); people feel improves code clarity.
note since c99, first example ill-formed. calls getdata without function having been declared. in c89 performed implicit int getdata(); declaration, since c99 removed. use compiler switches -std=c99 -pedantic test this.
Comments
Post a Comment