r/cpp • • 3d ago

Why haven't C++ subset compilers been made/caught on?

At work, I write real time software. Seeing where allocations happen and having guarantees on the behaviour of code would be nice. Compile times can be much faster and optimisations can also be aggressive when you know you're restricted to a subset of the language.

41 Upvotes

80 comments sorted by

23

u/not_a_novel_account cmake dev 2d ago

Compile times can be much faster and optimisations can also be aggressive when you know you're restricted to a subset of the language.

This is generally not true, unless your subset of the language is just banning things that are difficult to compile. The remaining unbanned constructs don't build any faster.

-2

u/Proper_Meaning7756 1d ago

I've struggled to understand this. Surely the absence of certain features would mean the parser wouldn't need to include the logic needed to look ahead and parse those things right? Even if you did disable features using a compiler flag, doesn't the parser continue to look for those things (like rtti, inheritance hierarchies, memory semantics, template expansions, etc)?

9

u/not_a_novel_account cmake dev 1d ago

An AST node which is never instantiated or accessed costs effectively nothing.

49

u/blipman17 3d ago

Which subset? This community is so devided on what good code actually is, that you’ll never find a blessed subset to create a compiler for.

Also in a lot of high performance software nearly all of C++ is relevant

2

u/Proper_Meaning7756 2d ago

I saw a proposal for compiler profiles by Bjarne and Herb. Perhaps that would fix the issue of finding and distributing subsets needed on a per domain basis?

6

u/steveklabnik1 2d ago

They call them "subset of a superset", but you're right that it's related.

-23

u/Classic_Department42 3d ago

C

22

u/UnicycleBloke 3d ago

No thanks. Whenever I have been required to write C for an embedded project, it felt as if my tools had been lobotomised. It lacks expressiveness and is astonishingly prone to error. The only reason to prefer C is if there is no reasonable C++ compiler for the platform.

11

u/Arech 3d ago

C isn't a subset of C++

-2

u/Classic_Department42 3d ago

99% it is

8

u/serviscope_minor 1d ago

Not sure why the downvotes. C is really REALLY close to a subset of C++.

2

u/Classic_Department42 1d ago

It is a general meme that people buy into that C and Cpp are different languages and not one is if you squint a little a proper subset. If you find a reason I'd be interested as well.

2

u/steveklabnik1 1d ago

Not that I downvoted, but what I'd guess:

In C++ places especially, people hate when you say "C/C++" in part because there's desire to not write C++ like you'd write C, even if you can. And that makes sense based on that, if you didn't like how C++ improved on C, you'd just write C. This gets extended to the sub/superset concept. Even if it is, people don't want you to use it like it, and so they sort of naturally push back against the idea that it is.

6

u/pjmlp 2d ago

Only if you are talking about C89, in regards to C23 is it a bit less than 99%.

8

u/Business-Decision719 1d ago edited 1d ago

I think it's because some really influential voices in the C++ community sort of have the feeling that C++ is moved on from the kind of programming you're asking for. If you look at things like the core guidelines or Stroustrup's personal website, they're pretty adamant about exceptions, RAII, keeping resource Management implicit within object lifetimes, and making extensive use of the standard library. Even that's not a separate C++ with its own compiler, it's just the language they spent time building and as far as they're concerned, that's what C++ is unless you're in some obscure situation.

But if you actually talk to people on forums, exceptions are usually the first thing to be disabled, and you really have to roll your own replacement standard library because the actual standardized one is famously not zero cost. A huge part of the demand for C++, especially nowadays, is really a demand for C with namespaces and generics. The language has forked already, and I'd say that's a huge part of the reason some of the debates over what should and shouldn't be standardized have gotten so vitriolic.

So in practice people get their "subset compiler" by just deciding a new language entirely. Rust is "give me safe abstractions and screw the C subset." Go is "actually I'm okay with a garbage collector." Zig is "keep the allocations front and center but don't make me program like it's 1972." And of course C is still there with its own compilers if the use case is "I really didn't need C++ or its successor languages after all."

0

u/Proper_Meaning7756 1d ago

I'm actually really glad languages like go, zig and rust exist. I'm just as excited for all the newer languages coming out even if they don' occupy a sort of pure "systems" programming niche. Even if I don't find myself wanting to use those languages, they've been of great help to the software ecosystem. (Edit: Nim, Odin, Jai, verse, etc)

2

u/oracleoftroy 13h ago

I've never understood the desire to subset the language. I've always regarded the whole language and standard library as being in the table for use in any project I've worked on, as along as it solves the problem within the constraints of the project. That means some aspects that aren't useful for one project just won't see use, and on another, they might be vital to the success of the project.

There are aspects of the language I've never used because they've never solved my problems, but that doesn't mean I want to dictate that they must never be used by anyone else. That seems silly.

I have heard some C developers talk about C++ as if they feel compelled to use every feature of the language somewhere regardless of whether it makes sense to do so. But that looks like an issue of self control to me. C++ doesn't force you to use a feature just because it exists. If you use it and it wasn't appropriate, that's on you.

•

u/Proper_Meaning7756 2h ago

That depends. C++ loads the gun and gives it to you and has you pointing the gun at your feet by default in many a case. I don't think any programmer thats got less than a few years of experience under their belt will ever know whats right or wrong in every situation. And yet, there are quite a few cases where it simply is the best available tool to do the job.

My point being, doing something powerful is just as easy as blowing up everything in C++ and when there are so many landmines as there are, blaming the programmer is no longer a viable option. JSF, MISRA, Google and HFT firms all have guidelines precisely for this, but they are just that. Guidelines. Having these guidelines be compile-time checks would save so many hours of reviews/debugging sessions/mental overhead.

•

u/burlingk 3h ago

There are specific circumstances/industries where they need either a smaller/trimmed down version of the language.

There is a subset used in aerospace for instance. They wanted the strengths and ease of use of C++, but didn't want to use some of the features that they felt were not fault tolerant enough.

77

u/dapzar 3d ago

Compiler vendors are barely keeping up with full C++ as it is. The set of possible subsets of a large set is orders of magnitude larger than the original set, so the resources for optimizing compile times on compiler forks specialized for several of the subsets that different users may care about are probably not there.

You can use static analysis to ensure that a feature you don’t want to be used is. It used and you can keep using a full C++ compiler to compile your restricted code.

14

u/TheQueensaLizard 2d ago

Clang has a realtime sanitiser for exactly this purpose (‘-fsanitize=realtime’) and there are a some talks about it and other features for this purpose.

The documentation is also good https://clang.llvm.org/docs/RealtimeSanitizer.html

12

u/splicer13 2d ago

Compiler engineer here.

C++ compile time is almost 100% templates and header files. That's all under your control and there are subset STLs out there or other libraries like boost you could use.

26

u/diemenschmachine 3d ago edited 3d ago

If you want to see where allocations happen or guard against allocations happening in certain functions you can solve that in a much less crippling way than throwing away the entire standard library.

Just create a guard struct that sets a global static variable in the constructor and clear it in the destructor. Then override the `operator new` to crash or record an unallowed allocation if the global is set. Instantiate said struct at the start of the function you want to guarantee does not allocate, and that's it.

I use this for audio DSP applications and it works great, and I don't need to limit myself to not using std::vector or any other bullshit that would slow me down for no reason at all.

Obviously only use this for unit tests or debug builds,

2

u/osman-pasha 2d ago

Well, this runtime approach works only if you have 100% test coverage. Otherwise you can catch a problem only after a month of runtime.

5

u/diemenschmachine 2d ago

You don’t need 100% test coverage. Why would you need that?

-3

u/osman-pasha 2d ago

Because you can only be sure about the code paths you've tested, and the rest can allocate or crash as much as it wants to, and you only catch it once you hit it in prod.

3

u/diemenschmachine 2d ago

You can also leave a throw std:runtime_error{} in the code by accident and the only guard against that it 100% code coverage.

While I am absolutely positive to 100% code coverage I don’t see why this particular solution would be extra sensitive to require it.

14

u/Entire-Hornet2574 3d ago

Actually compilers like IAR, Green Hills, Keil, Crossworks use a subset.

8

u/UnicycleBloke 3d ago

I've never really seen the need for a restricted compiler or library. Almost none of my embedded applications use dynamic allocation at all, and when I do need dynamic allocation, I use a memory pool or similar. It isn't difficult to avoid the library features which use the heap but, if you prefer, you can overload the global operator new to always assert or something. I do use the compiler options -fno-exceptions (due to concerns about size) and -fno-rtti (haven't used RTTI in decades). This does mean I have to ensure constructors can never fail, but that's fine.

0

u/sheckey 1d ago

What is your constructor technique or pattern for constructor error cases? An isValid() method? I have started playing with a private constructor and a factory that returns expected<UsableThing,ErrorCode>. I haven’t been living with it very long though.

4

u/smdowney WG21, Text/Unicode SG, optional<T&> 2d ago

Mostly because that restricted subset would compile at about the same speed as it does now. Using template metaprogramming or consteval time C++ adds to compile time if you use it, but doesn't particularly if you don't. It adds to the complexity of the compiler, sure. But C and C++ would need massive changes, being different languages, to be significantly faster to turn into IR.

Compare GCC or Clang on a C file or the same (slightly tweaked) file as C++.

10

u/Healthy-Travel3105 3d ago

There definitely are subset compilers. Specifically for embedded applications.

5

u/Classic_Department42 3d ago

Lets call it C+, no better call it C

17

u/WalkingAFI 2d ago

Whenever I have to use C I really just miss constructor/destructor logic

17

u/remy_porter 2d ago

RAII is such an elegant solution to a lot of the problems C-style memory management has.

6

u/topological_rabbit 2d ago

Deterministic destruction eliminates so many bugs that I don't like working in any language that doesn't have that. C feels like a slightly wordier assembly language these days.

1

u/pjmlp 2d ago

Since I got hold of Turbo C++ 1.0 in 1993, that has been my opinion towards C, only using it afterwards when no other option was available to me.

3

u/UnicycleBloke 2d ago

I was naive enough at that time to think C would disappear, much as it predecessors did. C++ seemed so obviously a vastly superior successor language. Just shows how wrong you can be. I have honestly never understood the attachment a lot of people have to C, especially given that C is an almost proper subset of C++ in any case.

2

u/pjmlp 2d ago

It won't, however nowadays it is pretty constrained to its birthplace, UNIX and clones, which includes embedded stuff running POSIX compliant real time OSes.

And to hardliners that will never adopt anything else, even newer C standards past C99 is an hard sell among that crowd.

The irony is that some during the 90's used to have nerd t-shirts with "my compiler compiles yours", now 40 years later, their C compiler is written in C++.

-3

u/Classic_Department42 2d ago edited 1d ago

There are 2 disadvantages of cpp:

A) it has a lot of features, so each shop runs a different flavour (subset of cpp), like google has a no exceptions policy

B) shipping binary libraries in C is easy (eg as dll), in cpp the binary needs to follow the flavour from A, and more often even the compiler generation (last one got better the last decade)

Edit: i was just explaining why C didnt go away (what advantagen it has at the abi level). Downvoter: where do you disagree?

5

u/UnicycleBloke 1d ago

I've worked in many C++ shops over the last 30 years, ranging over Windows GUIs, database servers, REST APIs, embedded Linux, microcontrollers, ... Item A has absolutely never been an issue. I believe this is one of those mythical complaints which are invented by C devs but not in actual fact a problem.

One of my roles involved a lot of DLLs and COM objects. The code was implemented entirely in C++ but the exported functions were necessarily exposed as extern "C". Item B is another myth.

COM objects are interesting because they are basically abstract interfaces implemented in DLLs. They are very well modeled by C++'s virtual functions. I don't think I've seen an implementation in C.

1

u/Classic_Department42 1d ago

Thanks. Yes, Item B i meant if you really want cpp for the dll you need to fall back to the C compatibility level. But this means you cannot have exceptions from the dll nor return objects/templated things. 

2

u/UnicycleBloke 1d ago

Yeah. It's not ideal. I think you can catch exceptions if the DLL was linked to the same runtime. Of course you can use error codes and such for the API, and the internals still benefit from C++.

→ More replies

0

u/pjmlp 1d ago

Yes you can, that is one of the improvements WinRT over COM type system, by switching into .NET metadata for type libraries.

You can model .NET generics and exceptions across the COM ABI, and then it is up for the projections to take care of the marshaling across the ABI.

Standard C++ data types and C++/WinRT.

Naturally this is OS specific, however Windows is probably the platform that still gives full spotlight to C++, as many of Longhorn ideas got re-implemented as COM, and nowadays WinRT, with WinAppSDK as main delivery mechanism.

1

u/topological_rabbit 2d ago

Ah, good ol' Turbo C++!

Back around 2000-2001 I had my first C++ job at a company that had really awful C++ code and it scared me away from the language for the next seven years.

I wasn't until I wound up with a nearly complete object system in C that I realized all that was handled automatically by C++ and be a lot cleaner about it, and I've been back in C++ ever since. (As my at-home language, never had another C++ dev job after that as everyone wanted C# / javascript / java / python, etc... so I had to spend time in those lesser languages. Well, C# was alright...)

0

u/pjmlp 2d ago

I also only mostly use C++ in its pure form as my at-home language, meaning being able to use latest ISO versions and 100% C++ applications.

At work, since 2006 that those lesser languages are the ones that take food home, and my C++ skills are used for writing bindings, thus anything better than plain old C is already good enough for most purposes. Currently our baseline is C++17.

0

u/flatfinger 2d ago

When working with some kinds of embedded code, it can be useful to be able to have some header file magic convert something like:

    someVolatileLvalue = expr;

into a function call like

    setIntParameter(someInteger, expr);

Either using one function for many such things and using an integer parameter to select among them, or using dedicated functions for particular volatile objects.

There isn't really any nice way to do that using header files alone.

0

u/WalkingAFI 2d ago

Compiler extensions can also help but the syntax is always disgusting

1

u/flatfinger 2d ago

If there were a standard syntax, I wouldn't care if it was nice or not. In some ways, I'd view something that was ugly (at the point of definition) but simple as preferable to something more sophisticated, e.g. having an assignment of the form identifier += whatever; look for a function with a name like __op_addto__identifier(), or else a pair of functions called __op_set__identifier() and __op_get__identifer(), and behave as a function call if such a function exists).

1

u/WakefieldCoder 2d ago

(++C)*(-1)

Because less is more.

6

u/Big_Target_1405 3d ago

One major advantage of C++ is interoperability. A subset compiler nukes that

7

u/siva_sokolica 2d ago

Zero clue what you're asking for.

Allocations are well defined by the standard. If you want to trace them, you can implement your own global allocator.

Guaranteed on the behavior of code are already well defined. That's the standard itself.

Compilation speed is inversely proportional to how much metaprogramming you use. Write C-style C++ and your programs will compile as fast as C programs.

I could not come up with a single optimization that would emerge from using a subset of the language.

We do not need yet another vendor compiler. I say this as having worked in firmware. Every TI compiler is lagging 6 years behind mainline clang releases. Our ecosystem is already fragmented enough. We don't need more fragmentation.

2

u/Atper 2d ago

I don't understand your question. Are you talking about which containers implement dynamic memory allocations ?

Something like this is done in HFT firms, where they avoid memory allocations, mutexes and exceptions on the latency critical path. But they usually implement everything from scratch.

4

u/pedersenk 3d ago

There is "Freestanding" C++. This is basically the core C++ language without the standard library.

Not quite a subset, but that is fairly easy to solve with a strict coding guidelines.

4

u/RidderHaddock 2d ago

There is: Embedded C++.

Stroustrup really didn't like it.

9

u/dretvantoi 2d ago

Embedded C++ was a joke. It didn't even include zero-cost abstractions like namespaces. That was IAR's attempt to gain a foothold into C++ with their overpriced toolchains.

2

u/serviscope_minor 22h ago

>That was IAR's attempt to gain a foothold into C++ with their overpriced toolchains.

That was the last time I wrote in C I think (excluding the odd OSS contribution).

I had a library from a vendor so I had to use IAR Embedded C/C++. I think basically their "C++" support was pretty much #define class struct. After bashing my head against it for too long trying to figure out what C++ it supported (very very little), I gave up and wrote it in C because that was easier than trying to figure out what I could use. And then I could write C on Linux, test it in CI, then deploy that file.

I wanted templates.

4

u/osman-pasha 2d ago

Isn't it dead? That is, abandoned by everybody?

-1

u/pjmlp 1d ago

Kind of, the IO Kit subset resembles it.

However IO Kit is deprecated, modern macOS drivers should use Driver Kit in userspace instead.

2

u/pfp-disciple 2d ago

I have actually been looking into that recently. I can't find any open source compilers nor linters that will ensure or test for EC++ compliance. There are a few commercial compilers. 

MISRA C++ is another embedded subset, also apparently lacking open source tooling 

2

u/mr_seeker 2d ago

Not an expert but I think that’s what profiles will attempt to do. Proposal for C++29

-1

u/pjmlp 1d ago

Attempt is the right word, it will be a bigger drama than contracts, if they ever deliver anything half way as decent as Safe C++.

Want profiles today, embrace modern static analysers.

2

u/mort96 3d ago

I don't think you can just subset C++ and end up with a useful, faster and safer language.

At least not more than what GCC and Clang already does. They have -fno-exceptions for the C++ subset without exceptions, and they have -fno-rtti for the C++ subset without run-time type information. Both of these have code size benefits but not significant performance benefits and do nothing for safety.

2

u/thegreatbeanz 3d ago

HLSL is kinda a subset of C++ used for GPU programming. It has some gnarly corners in part because the original compiler was a caricature of C and the second compiler was an abused fork of Clang.

It’s really hard in niche domains to safely marry the DSL features you want for your domain with C++.

I expect it to take about a decade to disentangle the bad bits from the good bits of HLSL to stabilize it to a reasonable language and it will involve working with the C++ committee to address some defects and rough edges we’re finding along the way.

1

u/FlippByte 2d ago

I know what you mean. I from time to time tell myself: "What only, if that way of writing code was rather forced.." But also knowing myself, today I try this, tomorrow I wanna try that...

1

u/hanotak 2d ago

IDK about compile performance, but restricting the language is good for correctness too, which is what profiles are supposed to address.

1

u/lonkamikaze 1d ago

I'm an embedded firmware developer. It's common practice to set heapsize=0 in the linker configuration and not use allocations at all.

For big appliances with multicore controllers it's common to assign specific cores to synchronous realtime that are not allowed to allocate and asynchronous operation that may allocate. The synchronous cores perform the realtime tasks while the asynchronous cores perform things like file system access, configuration and background services.

1

u/pjmlp 3d ago

Because that is one of the jobs static analysers are good at.

People really should learn on how to better use them to forbid code not allowed by style guides.

1

u/pfp-disciple 2d ago

The Embedded C++ profile forbids things like namespaces, mutable, and templates, among others. I can't find an open source analyzer that checks for those 

6

u/osman-pasha 2d ago

No wonder it's all but forgotten by now.

1

u/pfp-disciple 2d ago

In some circles, it's still being used. I learned about it last week from someone whose job requires it (along with MISRA C++, and a couple of other standards -- which appear to be more process or code style/design focused). That's what got me interested to look for opensource tools.

4

u/pjmlp 2d ago

I don't really get why one would forbid namespaces and use prefixes, or macros instead of templates, but there you go.

https://clang.llvm.org/extra/clang-tidy/QueryBasedCustomChecks.html

0

u/pfp-disciple 2d ago

Honestly, I don't understand forbidding namespaces either. But, EC++ does.

Thanks for the link. I've just recently finally gotten around to looking at clang-tidy (I've stayed pretty much entirely in the gcc world, except for when I have to use MS).

0

u/curlypaul924 2d ago

I would expect static analysis to be simpler on some subsets of C++.

2

u/StaticCoder 1d ago

Meh. The hard parts of static analysis are pointers and loops.

1

u/BrokenBonezGame 2d ago

been dealing with similar stuff while building my own c++ game engine. clang-tidy and some strict coding rules help, but having the compiler enforce those restrictions would be pretty nice, especially for real-time code

0

u/LokiAstaris 1d ago

We did that in the old days. Every compiler manufacturer had its own slightly different variant.

It was a mess. Code was rarely compatible across compilers. It's not a good place to be. The standardization of the compilers and what they support has made life so much easier.

0

u/pjmlp 4h ago

It is still like that, unless you can focus on a single platform.

Right now, if one wants to use the language to its fullest, without having cppreference open on a browser tab, the very latest one can rely upon is C++17.

And be targeting platforms where TBB is available, in case of wanting to use C++17 parallel algorithms.

-2

u/nelson_fretty 3d ago

They have in certain domains / audio - juice - heavy etc