Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C++
Article

The Ultimate (DLL) Header File

Rate me:
Please Sign up or sign in to vote.
4.84/5 (10 votes)
7 Nov 2000 174.8K   84   23
Here is the ultimate header file that makes multiple declaration compiler errors a thing of the past.

Introduction

Efficient and appropriate use of header files requires a few tricks. If you simply define a set of functions, everything works fine. No problems. If the file is included more than once because of a complex #include chain, you get redundant declarations. Most compilers, including the Microsoft C/C++ compilers, simply ignore these redundant function and variable declarations. However, if there are any class, typedef, struct, or some other declarations, the compiler will complain bitterly if they are seen twice, claiming they are duplication declarations. It does not choose to see if the structures actually are identical. So there is an idiom to avoid duplication declarations, which is to put the entire contents of the header file in an #ifndef, skipping the body if a symbol defined within the body is already defined. This works acceptably well for short files, but is a performance disaster for lengthy files, since each line of the file must be read. For standard header files, precompiled headers work well in eliminating this problem, but it is harder to justify putting your own headers into a precompiled header file since the effects of a simple change result in a massive recompilation (stdafx.h has to be recompiled). Microsoft has added a #pragma that means the header file is read only once. All of this is shown in detail below.

DLL Headers: Additional Complexity

When constructing a DLL, you need a header file to interface to it. However, the obvious solutions do not work as expected. For example, if you declare a function in a fashion so as to export it, you need to add __declspec(dllexport) to its declaration, and if you don't want name mangling, particularly important if you expect to use the DLL with straight C code as well as C++, you need to define it in the .cpp file as

extern "C" __declspec(dllexport) function-header
   {
    // ... whatever
   }

The problem with this approach is that the obvious solutions to the header file don't work.

The First Wrong Approach

The first attempt you might make is to declare, in the .h file

extern "C" function-prototype; // incorrect

This doesn't work because the compiler will complain that the prototype is incompatible with the declaration. What causes this is the prototype lacks the __declspec(dllexport) declaration. So, you say, I'll just add that in. So you get

extern "C" __declspec(dllexport) function-prototype; // incorrect

This doesn't work for a different reason. Although you will no longer get a warning when you compile the DLL, you will get a warning when you compile the application, because the declaration __declspec(dllexport) is incompatible with the use of the function call.

The Second Wrong Approach

At this point a couple workarounds present themselves. The first one you might consider is to use two header files, one of which has the __declspec(dllexport), and the other of which does not. This is a Bad Idea. The reason is that you lose the consistency checking you would get if you include the same header file into both the DLL compilation and the client compilation. For example, if you change the function to have a different parameter type, the compiler will complain unless you change the DLL's header file prototypes to correspond. But in this case, the DLL header file is completely useless, and might as well not exist, because there is a completely separate header file for the client. It remains uncorrected, and there is no cross-check against the actual module. You lose.

A workable but inconvenient approach

At this point, you could remove the __declspec(dllexport) declarations entirely. This means your one-and-only header file will be consistent with the source, but, whoops, the symbols are not exported. To get around this, you can add either the /exports:function command line switch to the linker command line, or use a .def file and add the function name to the EXPORTS section. This is a valid, correct solution, and it works, but you will find that it quickly becomes inconvenient, because you have to remember to add the function name declaration to the /exports switch or add the name to the .def file. Anyone who did DLLs or Windows programming in Win16 in the days before the __export keyword was added to that language will remember how bad this was. Those of you who did not, take our word for it, it was a real royal pain to deal with this. So I'm disinclined to use this solution unless there are other compelling reasons, which there rarely are.

The Ultimate Header File

This is a model which I have cut-and-pasted many times for every DLL I've built in recent years. I've added some comments to help explain and show visually what is going on, and you will probably want to remove these before actually using it.

The uniquename name is something of your own choice. It could be a simple text string, e.g., _DEFINED_MYDLL_HEADER, or you could use GUIDGEN to create a GUID. If you use GUIDGEN, create a "Registry Entry" format, which is 

{EBE7C480-A601-11d4-BC36-006067709674}

Remove the { }s  and replace the hyphens with underscores. This would give you a symbol like

_DEFINED_EBE7C480_A601_11d4_BC36_006067709674

which guarantees that you will never, ever have a conflict with any other header file.

#ifndef _DEFINED_uniqueheadername  //---------------1---------------+
#define _DEFINED_uniqueheadername  //---------------1---------------+
                                                                 // |
  #if _MSC_VER > 1000  //--------------2---------------+            |
    #pragma once                                    // |            |
  #endif //----------------------------2---------------+            |
                                                                 // |
  #ifdef __cplusplus  //---------------3---------------+            |
  extern "C" {                                      // |            |
  #endif // __cplusplus  //------------3---------------+            |
                                                                 // |
  #ifdef _COMPILING_uniqueheadername  //-----------4-----------+    |
    #define LIBSPEC __declspec(dllexport)                   // |    |
  #else                                                     // |    |
    #define LIBSPEC __declspec(dllimport)                   // |    |
  #endif // _COMPILING_uniqueheadername  //--------4-----------+    |
                                                            // |    |
  LIBSPEC linkagetype resulttype name(parameters);          // |    |
  // ... more declarations as needed                        // |    |
  #undef LIBSPEC   //------------------------------4-----------+    |
                                                                 // |
  #ifdef __cplusplus    //----------------5---------------+         |
  }                                                    // |         |
  #endif // __cplusplus  //---------------5---------------+         |
#endif // _DEFINED_uniqueheadername //-----------------1------------+

The explanation of the "contour lines" is as follows

  1. If the header file is actually processed, this is the traditional C idiom to keep it from being processed twice. The first time the file is included, the symbol _DEFINED_uniqueheadername is not defined, so the file is processed. The first thing it does is declare that symbol, so that in subsequent inclusions, the entire body of the file is skipped.
  2. This is a #pragma which is defined only for C compilers version 10.00 and later (note that the C compiler version and the VC++ version are not related numbers). If this #pragma is implemented, the inclusion of this file in a compilation creates an entry in an "included files table" for that compilation. Subsequent attempts to include this file in the same compilation first check this table, and if the filename is the same, the compiler doesn't even bother to open the file. However, you can't eliminate the contour 1 test, because this #pragma, for reasons best known only to its implementor, is case sensitive in the file name, even though the file name of the underlying operating system is case insensitive. It seems utterly silly that we should have two discrete behaviors, but since when has rationality and common sense affected what some programmers do?
  3. This contour is required to make the header file compatible with both C and C++. It assumes that you want C compatibility, and therefore that the function names should not have C++ "name mangling" applied. The downside of this is that you lose the ability to overload functions based on parameter types. If you are doing a C++-only DLL, you would not use this contour, and you would also eliminate contour 5. The __cplusplus symbol is defined for a C++ compilation but undefined for a C compilation.
  4. This is a funny contour. The #if/#else/#endif contour decides which form of __declspec to use for the declaration. The scope of the effect of this contour actually projects beyond the conditional and extends to the #undef, during which the symbol LIBSPEC is defined. Strictly speaking, you do not need to do the __declspec(dllimport); you could just define LIBSPEC as an empty macro. However, declaring __declspec(dllimport) does same one or two instructions on the linkage when it is finally resolved. Since, using this method, it costs nothing to add this slight efficiency, why not? Note that contour 4 is not needed for non-DLL files.
  5. This is the matching close brace to the structure created in contour 3. If you are doing a C++-only DLL, you would eliminate this as well as contour 3. 

Now, in the DLL itself, you have to do one thing: you must declare the _COMPILING_uniquename symbol before the #include. After that, you simply declare the function as shown.

#include "stdafx.h" // usually 
#define _COMPILING_uniquename
#include "myDLL.h"

extern "C" __declspec(dllexport) linkagetype resulttype name(parameters)
   {
     // ... whatever
   }

and you will not get any compiler conflicts. This will use the same header file for both the DLL and client, and all the Right Things will happen.


The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft.

Send mail to newcomer@flounder.com with questions or comments about this article.
Copyright © 1999 CompanyLongName All Rights Reserved
www.flounder.com/mvp_tips.htm

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Retired
United States United States
PhD, Computer Science, Carnegie Mellon University, 1975
Certificate in Forensic Science and the Law, Duquesne University, 2008

Co-Author, [i]Win32 Programming[/i]

Comments and Discussions

 
Suggestionwhich guarantees that you will never, ever have a conflict with any other header file. Pin
DaveGordon5-Feb-13 10:03
DaveGordon5-Feb-13 10:03 
GeneralRe: which guarantees that you will never, ever have a conflict with any other header file. Pin
Southmountain3-Feb-18 13:05
Southmountain3-Feb-18 13:05 
Questionhow to find the function prototype for any dll Pin
viduran17-Apr-07 20:28
viduran17-Apr-07 20:28 
hi,
give me idea that how to get the function prototype for predefined dll.
and the function that dll exports.
help me
AnswerRe: how to find the function prototype for any dll Pin
Joseph M. Newcomer21-Apr-07 19:28
Joseph M. Newcomer21-Apr-07 19:28 
GeneralRe: how to find the function prototype for any dll Pin
toxcct14-Nov-08 4:12
toxcct14-Nov-08 4:12 
Question_COMPILING_uniqueheadername, what for? Pin
Hunt Chang10-Aug-06 18:12
Hunt Chang10-Aug-06 18:12 
AnswerRe: _COMPILING_uniqueheadername, what for? Pin
Joseph M. Newcomer10-Aug-06 19:44
Joseph M. Newcomer10-Aug-06 19:44 
GeneralRe: _COMPILING_uniqueheadername, what for? Pin
Hunt Chang12-Aug-06 13:04
Hunt Chang12-Aug-06 13:04 
Questionhow to choose between DLLs at runtime Pin
Jesse Evans8-Nov-04 12:21
Jesse Evans8-Nov-04 12:21 
AnswerRe: how to choose between DLLs at runtime Pin
Joseph M. Newcomer8-Nov-04 18:04
Joseph M. Newcomer8-Nov-04 18:04 
GeneralRe: how to choose between DLLs at runtime Pin
Jesse Evans9-Nov-04 6:35
Jesse Evans9-Nov-04 6:35 
GeneralHello Sir Pin
ThatsAlok26-Oct-04 22:54
ThatsAlok26-Oct-04 22:54 
QuestionHow to extract DLL functions ? Pin
Defenestration4-May-04 14:30
Defenestration4-May-04 14:30 
AnswerRe: How to extract DLL functions ? Pin
Joseph M. Newcomer5-May-04 4:58
Joseph M. Newcomer5-May-04 4:58 
GeneralNo need for extern "C" declaration Pin
Tealc19-Aug-02 22:37
Tealc19-Aug-02 22:37 
GeneralRe: No need for extern "C" declaration Pin
Joseph M. Newcomer25-Aug-02 6:26
Joseph M. Newcomer25-Aug-02 6:26 
GeneralAlready exists Pin
2-Apr-01 5:36
suss2-Apr-01 5:36 
Generalyep Pin
Jonathan de Halleux9-Oct-02 0:34
Jonathan de Halleux9-Oct-02 0:34 
GeneralYet Another Approach Pin
20-Nov-00 19:45
suss20-Nov-00 19:45 
GeneralAnother solution Pin
9-Nov-00 9:20
suss9-Nov-00 9:20 
GeneralGoing further: Function Prototypes/Pointers Pin
9-Nov-00 0:56
suss9-Nov-00 0:56 
GeneralMFC-Code for Win32-DLL Pin
8-Nov-00 20:50
suss8-Nov-00 20:50 
GeneralNice! Pin
Jonathan Gilligan8-Nov-00 11:05
Jonathan Gilligan8-Nov-00 11:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.