C++ - Declaration vs. definition

Declaration comes first.


Declaration introduces a name into a translation unit (a unit of compilation, essentially a cpp and associated header files). It tells the compiler that a particular name (function, variable, class, enum, typedef, etc.) is available for use.

  // foward declare a function
  int main();
  
  // forward declare a class
  class CDog;
  
  // forward declare a global instance handle
  extern HINSTANCE g_hInstance;
  
  // include a header file declaration for class CPerson (the header file may contain a partial definition -- i.e. implementation, or no definition at all).
  #include "cperson.h"
  

In the example above, a call to function main() will compile successfully (though it may still fail to link). You can declare a pointer to a CDog object. You can use the g_hInstance global variable. You can use the CPerson object and call methods on it.


Definition is the full specification of a type, including it's implementation.

  // definition of function main
  int main()
  {
      return 0;
  }
  
  // definition of class CDog
  void CDog::Bark()
  {
      printf("woof");
  }
  
  // definition of global variable g_hInstance
  HINSTANCE g_hInstance;
  

Declaration is what the compiler needs. Definition is what the linker needs.

A type can be declared as many times as needed, but it must be defined only once.
E.g. You can declare 'extern HINSTANCE g_hInstance' in every file that needs it, but you must define the variable (and allocate storage for it) in only one compilation unit.

If you declare a name without defining it, you'll get an LNK1120 unresolved external linker error.
If you declare a name, and define it more than once, you'll get a LNK1169 one or more multiply defined symbols found linker error.


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath