Menu

Little lame question on Header files

2003-01-27
2012-09-26
  • Nobody/Anonymous

    Using C I cant have functions, initialize global vars or use expressions inside of .H files is that correct?

    Is it possible to do that using C++?

     
    • Anonymous

      Anonymous - 2003-01-27

      Your question reveals a misunderstanding of the pre-processor/compiler/linker tool-chain, otherwise you would not ask, because you would not want to do it!

      In either case (C or C++), it is not that you cannot do what you are suggesting, but simply that a) it is not good practice, and b) is unlikely achieve what you intended.

      Header files are for declarations rather that definitions or instantiations (with the exception of pre-processor macro definitions). You declare items in a header that will be defined elsewhere so that when the module is compiled, the compiler will be satisfies, and insert an unresolved symbol. The unresolved symbols are resolved by the linker.

      #include is a pre-processor directive, that simply inserts the referenced file at that location before passing the whole expanded source to the compiler itself.

      As such putting code or data instantiations in a header is not illegal (not in C or C++), but it will cause problems for the linker, Normally you include a header in more than one module (if you don't, the the declarations in the header need not be there, they could be in the c/cpp file itself and therefore hidden); if you were to include code and data instantiations in the header, that code and data would be duplicated in every module, and the linker would reject them as having duplicate symbols.

      This goes for C++ too, since it is a linker issue not a language or compiler issue.

      There are rare circumstances where you may want to #include definitions/instantiations, I have done this where the file included is code generated by a separate program - but in these cases I give the file a .c or .cpp extension, so that it is obvious to anyone maintaining my code (including myself) that I am doing something out-of-the-ordinary. In these circumstances it is important that either the generated code/data is only included in one place, or that all such definitions have the "static" modifier. The effect of the 'static' modifier is to make the function/data local to the module in which it is included. It the file is included in several modules there will be multiple copies of that code/data - which may or may not be what you intend!

       
    • Nobody/Anonymous

      Cliff,

      I have thought of the header file as essentially an interface, something like the package specification in Ada is.

      Of course, I have been known to be wrong...

      :-)

      Wayne

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.