10 ms·
Some of these recommendations are awesome, others aren’t good, IMO. > Always prefix your names to avoid name collisions Solved by C++ namespaces. > Use heade
by Const-me 7y ago
Some of these recommendations are awesome, others aren’t good, IMO.
> Always prefix your names to avoid name collisions
Solved by C++ namespaces.
> Use header guards instead of #pragma once.
#pragma once is supported by all mayor compilers, header guards can introduce bugs, also #pragma once builds measurably faster: https://github.com/electronicarts/EASTL/blob/3.15.00/include/EASTL/vector.h#L64-L66 https://github.com/electronicarts/EASTL/blob/3.15.00/include...
> Expose constants to the user using constexpr variables.
Modern C++ has strongly-typed scoped enums for such constants.
- kd5bjo 7y agoC++ features don’t help when you’re programming in straight C, as the article advises.
- pjmlp 7y agoOther than UNIX like kernels and tiny PIC micro-controllers no one else should still be programming in straight C in 21st century.
- jstimpfle 7y agoIf people choose to and it gives them joy, and they are productive and even learn valuable things, why not let them be?
- pjmlp 7y agoBecause if someone else happens to use that library, it might blow up on their face, e.g. WhatsApp dependency on android-gif-drawable. https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932 https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1193...
- deleted 7y ago[deleted]
- jstimpfle 7y agoAre you looking for a safe way to use your computer? Turn it off. Other than that, I'm not surprised the file in question is C. Even ignoring the fact that it was you to get the link. And even ignoring that it's about a security problem... Other than that, from a user perspective, software written in C is among the most reliable software I'm using. I'm looking at Linux, vim, xterm and so much of the infrastructure that I don't even know by name. Some people value "security" more than they value the beauty of a nice, a maintainable, or a practical program. That's ok as far as I'm concerned...
- pjmlp 7y agoThe guys attending the Linux Kernel Security Summit seem to think otherwise, plenty of stuff there to entertain yourself.
- jstimpfle 7y agoSure there is. But never be blinded, Linux is very performant and rock solid from an end user's viewpoint. Sometimes it helps putting things into perspective.
- pjmlp 7y agoIndeed, https://msrc-blog.microsoft.com/2019/06/14/prevent-the-impact-of-a-linux-worm-by-updating-exim-cve-2019-10149/ https://msrc-blog.microsoft.com/2019/06/14/prevent-the-impac... https://security.googleblog.com/2019/08/adopting-arm-memory-tagging-extension.html https://security.googleblog.com/2019/08/adopting-arm-memory-... https://kernsec.org/wiki/index.php/Kernel_Self_Protection_Project/Work https://kernsec.org/wiki/index.php/Kernel_Self_Protection_Pr... Seatbelts and helmets are also a nuisance, maybe we should get rid of them, that is my perspective.
- jstimpfle 7y agoIf you like random links, here is another one... https://news.ycombinator.com/item?id=21741504 https://news.ycombinator.com/item?id=21741504
- kd5bjo 7y agoThat may be so, but the central thesis of the article is that C is the still the appropriate language in which to write libraries for interoperation. If you believe otherwise, I suspect that a rebuttal of the author’s arguments in favor of C would be well-received as a top-level comment here— there seem to be a lot of people that agree with you, but nobody has yet stated why they hold that opinion.
- Const-me 7y ago> but nobody has yet stated why they hold hat opinion. I did, in my first comment. C++ namespaces lead to much more readable code, compared to these prefixed names. C++/11 scoped enums eliminate a class of bugs: when you have many different constants on the API surface, multiple functions accepting them, and erroneously use the constant of a wrong function. Example: enum Lod { Low, High }; enum SomethingElse { Other }; void setLoD( enum Lod v ); void bug() { setLoD( Other ); }
- kd5bjo 7y agoEspecially with this expanded commentary, you do show some advantages of C++ over C, but you have only addressed the advice for how to proceed once you’ve chosen C and not the author’s reasons for preferring C to C++ (or any other language): — Every language out there has a way to call into C — If your code is slower than C, someone will rewrite it in C. — If your library is written in C it means it can be used on any OS, console or mobile device and even on the web. — Not everyone wants to use C++ (some prefer C). — It is easier in general for a C++ user to use a C library than it is for a C user to use a C++ library. — C++ is not as easy to write wrappers for in other languages. — Unless you limit which C++ features you use (to the point where you are pretty much left with C) a lot of people won’t be able to use your library. PS. If your original comment had been phrased the way you put it here I might have made the same comment, but I would not have downvoted it. Here, you’re at least providing some supporting evidence for your assertions which makes it a much more valuable contribution to the conversation.
- Const-me 7y ago
- starsinspace 7y agoI agree that "straight C" is not the best choice anymore... but C++ isn't great either. It inherits most of C's weaknesses and for libraries, it makes it very difficult to use the code from languages other than C++. By making a library in C++ you are basically limiting it to being used only in C++ projects. (Yes, wrapper generators for C++-to-whatever exist, but my experience with using e.g. Qt from other languages has always been pretty terrible). Even in 2019, the C ABI is the one universally agreed-upon cross-language ABI for languages compiled to native code.
- pjmlp 7y agoIn what concerns security, both should be nuked. However given that at least C++ does support ways to tame C, after all the whole purpose was for Bjarne never to repeat his Simula into BCPL rewrite experience ever again, it is up for security conscious to decide what legacy they want to leave, when the option is between both those languages. On the other hand maybe C should be used to write Skynet, so that we stand a chance.
- huhtenberg 7y agoReading through your comments the only take-away appears to be that you just really don't like C for whatever reason. C is a perfectly fine language for tasks of all kinds. The fact that it expects programmers to take greater care when using it is not a reason enough to dismiss it as a general-purpose language. Not everyone needs (or wants) to ride a tricycle wearing knee pads and a helmet to get from A to B.
- pjmlp 7y agoAh the old straight jacket argument against computer security, never gets old. The reason is very simple, the billions of wasted money fixing security exploits caused by industry's adoption of C. Morris worm is more than 30 years old, and the old ways can still be used to attack modern systems that people insist in writing using C. https://msrc-blog.microsoft.com/2019/06/14/prevent-the-impact-of-a-linux-worm-by-updating-exim-cve-2019-10149/ https://msrc-blog.microsoft.com/2019/06/14/prevent-the-impac... https://support.apple.com/en-us/HT210348 https://support.apple.com/en-us/HT210348 https://msrc-blog.microsoft.com/2019/07/16/a-proactive-approach-to-more-secure-code/ https://msrc-blog.microsoft.com/2019/07/16/a-proactive-appro... https://kernsec.org/wiki/index.php/Kernel_Self_Protection_Project/Work https://kernsec.org/wiki/index.php/Kernel_Self_Protection_Pr... https://security.googleblog.com/2019/08/adopting-arm-memory-tagging-extension.html https://security.googleblog.com/2019/08/adopting-arm-memory-...
- sharpneli 7y agoAnd then there is things like windows.h defining max which breaks std::max. Sure that one has another define which prevents it but not all libraries have. C++ defines don’t respect namespaces so you are pretty much screwed in anycase.
- Const-me 7y agoThe OP’s advice to avoid macros in the library’s API is a good one. Please read my previous comments, it begins with “Some of these recommendations are awesome”. BTW, you can disable these windows.h macros by defining NOMINMAX. I usually do, because I prefer min/max from <algorithm>; in some edge cases std::min / std::max can be twice as fast because compiler guarantees to compute arguments exactly once.
- rehemiau 7y agoC++ is not being used by all indie game developers so I imagine the article was written with that in mind, that the library needs to work with C code as well.
- jstimpfle 7y ago> Solved by C++ namespaces. I've never understood what's the practical difference between NS::foo() and NS_foo() with regards to preventing name collisions. Can someone enlighten me? I know some disadvantages of the namespacing variant, though. There are now multiple names for the items defined in the namespace: the qualified one and the unqualified one. The latter is often not unique in practice, since the programmer relies on the qualified name for uniqueness. In effect, making simple text searches for identifiers is very unreliable. Note I do use IDEs, but I also code in vim, and I need to do simple text searches even when working in Visual Studio. Additionally, there's no guarantee that there are no spaces around the scoper. I believe "NS :: foo" is just as valid, which makes me uneasy with regards to text search, as well. Another issue I have: $ cat test.cpp namespace NS { int foo() { return 0; } }; $ g++ -c -o test.o test.cpp $ nm test.o 0000000000000000 T _ZN2NS3fooEv # I hate my life > Modern C++ has strongly-typed scoped enums for such constants. I haven't found those working for me. Apart from the namespacing issue described above, I have issues with explicit enum types. One issue is that I often need to put sentinel / "missing" values (typically the value is -1) where an enum value is expected. Even more often, I want to iterate over the values of an enum. C++'s enum "type safety" makes working like this really unergonomic. The way I go about this is I don't even use names for my enum types, and I fully qualify the enumeration values. enum { FPGAPARAM_BLA, FPGAPARAM_BLUB, FPGAPARAM_FOO, NUM_FPGAPARAM_KINDS }; struct ASDF { int fpgaparamKind; // obvious what kind of values are expected here... }; for (int i = 0; i < NUM_FPGAPARAM_KINDS; i++) { struct ASDF asdf; asdf.fpgaParamKind = i; do_asdf(&asdf); } In programming, the slightest mistakes, like putting a "-" instead of a "+", result in program bugs. These mistakes are much more likely to be made (and much harder to spot) than mistakes involving enum values from the wrong set. I won't let programming ergonomics be ruined in the name of "type safety".
- Const-me 7y ago> what's the practical difference between NS::foo() and NS_foo() with regards to preventing name collisions. They both do the job. There’re 2 practical differences. 1. You can write `using namespace` inside functions or the whole .cpp files. This often makes the consuming code more readable. 2. Sometimes you want to replace implementations. With prefixes it gonna be massive changes likely to introduce new bugs. With namespaces, replace `using std::vector` with `using eastl::vector` and you’re done. > Even more often, I want to iterate over the values of an enum. I only need to do that rarely. When I do, I cast types like this: enum struct eParamKind : uint8_t { Bla, Blub, Foo, valuesCount }; for( uint8_t i = 0; i < (uint8_t)eParamKind::valuesCount; i++ ) { const eParamKind pk = (eParamKind)i; // Whatever } > I won't let programming ergonomics be ruined in the name of "type safety". I disagree on ergonomics. VS makes much easier to consume API with strongly typed enums: ePar<Ctrl+Space>::f<Enter>, to type eParamKind::Foo It’s similar with namespaces versus prefixes BTW, IDE will first auto-complete the namespace, then only list members of that namespace once you type the `::` Update: another C++ feature relevant for game development is overloaded operators. Games often do non-trivial amount of math on small vectors, matrices and quaternions. Overloaded operators make sense for them.
- LucaSas 7y agoHi, thanks for your feedback. I am the original author. Regarding prefixes, I advice that you start by writing the library in C and then wrap it in C++ for a variety of reasons that you might want to consider. In C++ you should indeed always use namespace. Header guards have the advantage over pragma once that they are standard and you can also use them to check if a library is included. I might remove that since maybe it's not that important and people might different views. Regarding constants, I was referring to things such as numeric constants for which you would constexpr in C++. Maybe I can be more explicit there. Thanks for the feedback.
- Const-me 7y agoI advise you start by writing the library in C++ and then wrap it in C if you need C ABI of the library. It’s very hard to write correct C code which does IO and supports multithreading. Take a look at Microsoft’s implementation of fprintf, copy-pasted from Windows 10 SDK: https://gist.github.com/Const-me/f1bb320969adde6c79694265ea644b9d https://gist.github.com/Const-me/f1bb320969adde6c79694265ea6... They use RAII to set & revert the locale, and to lock RAM buffer to avoid corruption by another threads. They use C++ lambda for exception handling. They even use C++ template to avoid code duplication between printf and wprintf. But these C++ shenanigans are not exposed to user, user calls their `printf` (possibly in a code built by C compiler) and it just works.
- huhtenberg 7y ago> It’s very hard to write correct C code which does IO and supports multithreading This is just a random unsubstantiated statement. There's nothing particularly "hard" about writing IO libraries that is language-specific. Multithreaded or not.
- Const-me 7y agoWhen you do IO and multithreading, functions often need to acquire and release stuff: mutexes or other locks, resources, locales. Even more so in videogames, e.g. OpenGL code often calls glMapBuffer / glUnmapBuffer many thousand times each frame. The hard part is making sure you release stuff every time you acquire stuff, exactly once. C++ RAII makes it almost trivially simple, but standard C has nothing comparable. When you only targeting gcc and clang can use __attribute__(cleanup) in C, it helps but still it’s more limited and more error prone compared to destructors.