0

I am programming with abstraction of the data types. This means in my header files I declare my struct pointers and their related functions like so:

application.h

    typedef struct APPLICATION_Context *APPLICATION_Context;

    extern APPLICATION_Context appContextConstruct;

    extern void appContextAddMember(int member);

and in the source file:

application.c

    #include "application.h"

    struct APPLICATION_Context{
        int member0;
        int member1;
        int member2;
    };

    extern APPLICATION_Context appContextConstruct;

Two questions from this set-up:

  1. Why, in the header, do I not have to declare the typedef'd struct as extern? It should also be visible outside the header!

  2. Do I need to repeat the 'extern' keyword in the source file?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
hewi
  • 1,274
  • 3
  • 17
  • 32
  • The use of the `extern` keyword makes the difference between a *declaration* and a *definition*. – Some programmer dude Dec 02 '15 at 07:25
  • I can answer the questions, but it is not clear what you are trying to do with this code, it doesn't make much sense. Are you trying to create private encapsulation through incomplete/opaque type? Are you trying to create some sort of "singleton" object? – Lundin Dec 02 '15 at 07:35
  • private encapsulation through incomplete type – hewi Dec 02 '15 at 07:38
  • See [Is it a good idea to typedef pointers?](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) to see why it is not a particularly good idea to do as you did. – Jonathan Leffler Dec 02 '15 at 07:43
  • 1
    @Jonathan Leffler - I did read lots already, and it seems that it is a good idea as I did. Why would you not advise to do it this way? – hewi Dec 02 '15 at 11:09
  • See the question and answers already cross-referenced; that' s why. – Jonathan Leffler Dec 02 '15 at 13:43

1 Answers1

1

why, in the header, do I not have to declare the typedef'd struct as extern? it should also be visible outside the header!

A typedef is visible to any file including your header. Don't mix up typedef with variable declarations.

In fact, you shouldn't need to use extern at all, it is a keyword that should be avoided, since it means you are using global variables, which is poor design.

extern in front of function prototypes is superfluous.

Also, never hide pointers behind typedefs.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 1
    "Also, never hide pointers behind typedefs." Could you provide documentation on this statement – hewi Dec 02 '15 at 11:07
  • @hewi You may want to read [this](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) – Mohit Jain Dec 03 '15 at 05:08