The Ultimate (DLL) Header File

本文详细探讨了在创建DLL时如何正确使用头文件,避免重复声明和编译问题。介绍了几种错误的方法,如只包含函数原型导致的不兼容,以及使用两个不同头文件的缺点。提出了一种终极头文件解决方案,通过条件编译和特定宏定义,确保在C和C++中都能正确导出函数,同时避免了重复包含和名称修饰问题。
摘要由CSDN通过智能技术生成
 

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 &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值