Nick
Nick

Reputation: 308

Why the compiler issues no error for erroneous extern declaration?

On file1 I've defined the variable args as:

CLA args;

On file2 I've declared it as:

extern CLA* args;

The program would compile with both gcc and clang with no errors, and no errors would appear on valgrind either. There was a problem though: On file2 the function fprintf(args->output, ...) would not print anything. Why there were no errors issued?

Upvotes: 1

Views: 242

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

The program would compile with both gcc and clang with no errors

Because each C file is compiled independently. When the resultant object files are linked, the linker has only symbol names. It does not know the types associated with those symbols.

This is one of the reasons1 that C++ uses name mangling: the type of the symbol is embedded in its name, so if there is a mismatch, link failure will occur.

This is why you either don't use globals, or you declare them in header files, and include that header file everywhere you reference said global, including the unit that defines it.

There is never a reason for extern to show up in a .c file; only in a .h file.

and no errors would appear on valgrind either.

We haven't seen your source code so we can't know how you might be using said variable incorrectly in such a way that valgrind would detect it.


1 - The other, primary reason is to support overloaded functions.

Upvotes: 5

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Do the following instead:

Create a header file, let's call it globals.h. It should look similar to this:

#ifndef GLOBALS_H
#define GLOBALS_H

/* include whatever you need, declare the CLA type */

extern CLA *args;

/* define/declare/etc. whatever you need here. */

#endif

In the first file, do:

#include "globals.h"

In the second file, do:

#include "globals.h"

/* rest of code here */

CLA *args = NULL;

/* more code here */

Upvotes: 2

Related Questions