为了拥有一个干净的代码,使用一些OO概念可能很有用,即使在C中.我经常编写由一对.h和.c文件组成的模块.问题是模块的用户必须小心,因为C中不存在私有成员.使用pimpl习惯用法或抽象数据类型是可以的,但它添加了一些代码和/或文件,并且需要更重的代码.我讨厌在不需要时使用访问器.
这是一个想法,它提供了一种方法,使编译器抱怨对"私有"成员的无效访问,只需要几个额外的代码.我们的想法是定义两次相同的结构,但为模块的用户添加了一些额外的"const".
当然,使用演员阵容仍然可以写"私人"成员.但关键是要避免模块用户的错误,而不是安全地保护内存.
/*** 2DPoint.h module interface ***/
#ifndef H_2D_POINT
#define H_2D_POINT
/* 2D_POINT_IMPL need to be defined in implementation files before #include */
#ifdef 2D_POINT_IMPL
#define _cst_
#else
#define _cst_ const
#endif
typedef struct 2DPoint
{
/* public members: read and write for user */
int x;
/* private members: read only for user */
_cst_ int y;
} 2DPoint;
2DPoint *new_2dPoint(void);
void delete_2dPoint(2DPoint **pt);
void set_y(2DPoint *pt, int newVal);
/*** 2dPoint.c module implementation ***/
#define 2D_POINT_IMPL
#include "2dPoint.h" …
Run Code Online (Sandbox Code Playgroud) 我有一个非常大的C和C++代码(~200k loc),它广泛使用了糟糕的宏:
/* ... */
#define PRIVATE static
#define BEGIN {
#define END }
/* ... */
#define WHILE(e) while (e) {
#define DO /* yep, it's empty */
#define ENDWHILE }
/* and it goes on and on, for every keyword of the language */
Run Code Online (Sandbox Code Playgroud)
这是事情,我想摆脱那个愚蠢的标题,清理代码,并正确地缩进它.
起初,我想用一个简单的方法sed
来替换所有这些宏,但似乎并不那么简单.
这种情况WHILE
很成问题(其他陈述也是如此).我不能替换WHILE
为juste while
,因为开口的花括号将会丢失.当然,由于DO
宏没有做任何事情,它并不总是出现在代码中.因此,取代DO
通过{
不会做的伎俩.
我也不能使用结束语,因为条件通常分为多行:
WHILE (clsr_calibragedf_tabdisque.tab_disque[indice_disque].tab_date[indice_date] NE
clsr_calibragedf_tabdate [indice].date) DO
indice ++;
ENDWHILE
Run Code Online (Sandbox Code Playgroud)
我能想到的最好的解决方案是C预处理器,它只能替换特定的宏,而不能扩展#include
指令或其他宏.但我找不到那样的东西.
任何的想法?