In C++, we have the abstraction and data hiding. Can we achieve this through C?
Define your struct in a .C file, and only 'forward declare' the struct in your header.
So your .C file could contain this:
struct Car
{
char *brand;
int maxspeed;
};
And your .H file could contain this:
typedef struct Car *CarHandle;
Then write functions to manipulate the Car (setters, getters, ...) and put them in the same .C file as where the struct is defined. Of course, the function prototypes should be put in the header.
Now the callers can use the CarHandle and the functions that operate on the CarHandle, but never see what's inside the Car struct.
You can using incomplete, and derived types, similar to the "opaque data" concept in C++. This is a pretty well written article on the subject.
you can do it with static (global) variables and extern functions to manipulate them.
As Peter Miehle mentionned, you can create variables and functions that are private to a module (often the same as file, I suppose depending on the compiler).
You could compare modules to classes.
static
variables are only accessible from within the module. You can also have the equivalent to private functions by declaring functions as static
within a module.
The difference between this and real classes is that you can have only one instance. But with little work, you can also mimic the implementation of several instances.
The High and Low-Level C article contains a lot of good tips. Especially, take a look at the "Abstract Data Types" section.
See also: What methods are there to modularize C code?
精彩评论