top | item 36759240

(no title)

mojosam | 2 years ago

I think there’s a better example, but whether it applies it depends on one of two major divisions of C code: that designed to run on systems with a MMU (as typically used for Linux and other large OSes) — where virtual memory makes dynamic momory allocation practical — and those without — which today is primarily the very large world of embedded devices.

For the latter, the industry best practice is to avoid malloc(), except maybe at init time, and instead allocate memory statically. And in that use case, you break your code into modules, which can contain private data, public data, private functions, and public functions.

In other words, building an app out of C modules is a lot like building an app in a more modern language just using static classes, with no instantiation. And that design pattern — which is extremely common in the embedded world — we have a direct equivalent to the “private” qualifier, which is “static”, which restricts the rest of the app from accessing so-marked file-scope variables and functions.

Where this breaks down — as always with C — is when you need multiple instantiations of a module, which modern programming languages refer to as an object. The closest we can get in C is to pass the module’s public functions a struct with some sort of data structure containing the object’s n9n-static data. And the author explains, there are standard ways make that data structure opaque to calling code, but those are definitely workarounds to language shortcomings.

But the bottom line is that those language shortcomings — the lack of objects and a private qualifier for its members — are only shortcomings if you need those features, and in the embedded world, most applications don’t, they only require all the advantages offered by C. So as always, this is about picking the right language for the project, there’s no one size fits all.

discuss

order

No comments yet.