user3180902
user3180902

Reputation:

Is `extern` keyword is optional in c99 standards?

The first file is

/* OTHER.C */
#include <stdio.h>
#include <stdlib.h>

int i=35;
int fun1()
{
    i++;
    printf("%d\n",i);
    return 0;
}
int fun2()
{
    i--;
    printf("%d\n",i);
    return 0;
}

The second file is

/* MAIN.C */

#include <stdio.h>
#include "other.c"

int main()
{
    printf("%d\n",i);//WORKING FINE EVEN WITHOUT THE USE OF extern int i;

    fun1();//working fine

    fun2();//working fine

    getch();
    return 0;
}

After #include "other.c" in main.c , variable i along with fun1() and fun2() is working fine even without declaring it in main.c as extern int i and extern int fun1() and extern int fun2().

But in old compilers like turbo c, it shows error undeclared variable i.

So is this a additional feature added by C99 standards?

Upvotes: 0

Views: 206

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

What the #include preprocessor directive does is to actually and physically include the file at the place of the #include.

The compiler proper handles what is called translation units, which is the output of the preprocessor after all includes and macro replacements.

All this means that the compiler doesn't see different files, it just sees one large file, which in your case contains the code from other.c.

The usual way to handle things like this is to make a header file, e.g. other.h that the main file would include, and then contains the function prototypes (declarations). Then you let the build system generate two object files, one per source file, and link the object files together into a single executable.

If you're using gcc it could most easily be done like this:

$ gcc main.c other.c -o myprogram

This tells the compiler to compile the files main.c and other.c to temporary object files, which are then linked together to create the myprogram executable.

For this to work you might want to make a header file that declares the needed things:

/* OTHER.H */
#ifndef OTHER_H
#define OTHER_H

extern int i;
int fun1();
int fun2();

#endif

In the main.c file #include the header instead of the source file.

Upvotes: 4

Related Questions