Wednesday, July 7, 2010

C guideline: Extern declarations

One thought, as I was browsing through tons of bad code I have here at hand:

The C programming language allows you to write extern declarations quite everywhere. In the C file, in the function, even inside your 'for in for in for'. This usually tends to show the lack of structure and understanding of what should stay where. Externals, like globals, are bad code, so you might want to rethink the whole code you're working on.

If you still want to use it, probably the only place where you should be allowed to use them is in header files. Adding extern declarations in code may add unforeseeable linking problems, since the declaration of the original item might lie in a different module. Logically, the extern declaration is part of the interface of a module, thus it should lie in the header file that you include to access the module functionality.

If you want to get rid of this, you can simply add for the globals that you want to access setters and getters, depending on what you need. It would be the cleaner version anyway, and it will help you refactor things very fast and easy.

So as a guideline: don't use extern declarations in your C file. Move it in the header file or remove the need of the extern declaration altogether.

No comments:

Post a Comment