如何写出专业的C头文件
做到专业,应该是每个职业程序员应该要求自己做到的。让我们看看lua是怎么写头文件的。1.License AgreementLicense Agreement应该加在每个头文件的顶部。Lua Sample: /*** $Id: lua.h,v 1.175b 2003/03/18 12:31:39 roberto Exp $** Lua - An Extensible Extension La
·
做到专业,应该是每个职业程序员应该要求自己做到的。
让我们看看lua是怎么写头文件的。
1.License Agreement
License Agreement应该加在每个头文件的顶部。
Lua Sample:
/*
** $Id: lua.h,v 1.175b 2003/03/18 12:31:39 roberto Exp $
** Lua - An Extensible Extension Language
** Tecgraf: Computer Graphics Technology Group, PUC-Rio, Brazil
** http://www.lua.org mailto:info@lua.org
** See Copyright Notice at the end of this file
*/
** $Id: lua.h,v 1.175b 2003/03/18 12:31:39 roberto Exp $
** Lua - An Extensible Extension Language
** Tecgraf: Computer Graphics Technology Group, PUC-Rio, Brazil
** http://www.lua.org mailto:info@lua.org
** See Copyright Notice at the end of this file
*/
2.guard define
整个头文件应该在guard define之间
#ifndef lua_h
#define lua_h
#endif
#define lua_h
#endif
另外,如果这个头文件可能给c++使用,要加上
#ifdef __cplusplus
extern " C " {
#endif
/* The lines within extern "C" */
#ifdef __cplusplus
}
#endif
extern " C " {
#endif
/* The lines within extern "C" */
#ifdef __cplusplus
}
#endif
3.尽量不要在头文件中暴露数据结构
这样可以用户对你的实现的依赖,也减少了用户的编译时间
typedef
struct
lua_State lua_State;
LUA_API lua_State * lua_open ( void );
LUA_API void lua_close (lua_State * L);
LUA_API lua_State * lua_open ( void );
LUA_API void lua_close (lua_State * L);
可以看到虽然用户会一直使用lua_State,但是并不知道lua_State的结构是什么
从一个使用lua的例子程序可以看出:
#include
"
lua.h
"
#include " lauxlib.h "
#include " lualib.h "
int main( int argc, char * argv[])
{
lua_State * L = lua_open();
const char * buf = " var = 100 " ;
int var ;
luaopen_base(L);
luaopen_io(L);
lua_dostring(L, buf);
lua_getglobal(L, " var " );
var = lua_tonumber(L, - 1 );
lua_close(L);
return 0 ;
}
#include " lauxlib.h "
#include " lualib.h "
int main( int argc, char * argv[])
{
lua_State * L = lua_open();
const char * buf = " var = 100 " ;
int var ;
luaopen_base(L);
luaopen_io(L);
lua_dostring(L, buf);
lua_getglobal(L, " var " );
var = lua_tonumber(L, - 1 );
lua_close(L);
return 0 ;
}
4.函数声明前加XXX_API已利于拓展
Lua的例子
#ifndef LUA_API
#define LUA_API extern
#endif
LUA_API lua_State * lua_open ( void );
#define LUA_API extern
#endif
LUA_API lua_State * lua_open ( void );
如果定义了LUA_API就是给LUA内部使用的
如果没定义LUA_API就是for user 的
写Window dll程序经常会用到
#ifdef DLLTEST_EXPORTS
#define DLLTEST_API __declspec(dllexport)
#else
#define DLLTEST_API __declspec(dllimport)
#endif
#define DLLTEST_API __declspec(dllexport)
#else
#define DLLTEST_API __declspec(dllimport)
#endif
5.宏的定义
尽量使用括号来包住所定义的对象
#define
LUA_TNONE (-1)
#define lua_register(L,n,f) /
(lua_pushstring(L, n), /
lua_pushcfunction(L, f), /
lua_settable(L, LUA_GLOBALSINDEX))
#define lua_register(L,n,f) /
(lua_pushstring(L, n), /
lua_pushcfunction(L, f), /
lua_settable(L, LUA_GLOBALSINDEX))
6.目录结构
一般应该使用一个单独的include目录来包含要发布的头文件,但不应该把内部使用的头文件包含进去。
Lua 的 include目录只包含了三个头文件
lauxlib.h , lua.h, lualib.h
非常简洁
更多推荐
已为社区贡献1条内容
所有评论(0)