Created
January 18, 2022 00:18
-
-
Save bradenbest/a94df4a71c51104e3735dae119317cf9 to your computer and use it in GitHub Desktop.
C++ Killer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cppkill - for when people won't stop attempting to compile your | |
// C code with a C++ compiler and complaining about compile errors | |
#ifndef CPPKILL_H | |
#define CPPKILL_H | |
#ifdef __cplusplus | |
#error This is C code, so please use a C compiler. Thanks :) | |
#endif | |
enum yes_this_is_valid_in_c_thank_you { | |
class, this, extends, | |
virtual, template, typename, | |
const_cast, static_cast, reinterpret_cast, | |
using, namespace, std, /* ;) */ | |
boost, new, delete, | |
throw, try, catch, | |
mutable, requires, explicit | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In all seriousness, it's perfectly valid to mix C and C++ code, but there's a right way and a wrong way to do it.
The right way is to write the code separately and let the build system choose the compiler, making sure to wrap
#include
s of C headers inextern "C" { ... }
in C++ files and to compile the object files together using the C++ compiler. Let the build system figure it out.The wrong way is to write code that attempts to satisfy both compilers at once. In order to do this, you have to restrict yourself to only the parts of C and C++ that happen to overlap, which is not very useful. You lose most of the functionality of both languages (believe it or not, C++ is not even remotely close to being a superset of C), as you have to use only parts that both overlap and behave the same. And on top of that, you'll have people like me criticizing you for writing polyglot code. It's not uncommon to see constructs such as this in beginner code:
This is bad for several reasons. Casting malloc's return value loses the benefits of C's weak typing and violates DRY as the type is being needlessly repeated. Even if one realizes that
sizeof
is a compile-time operator and thussizeof *array
is preferable, the type is still being repeated in the cast. C makes an explicit exception for implicit casts to and fromvoid *
because void pointers are the generic type. Not only that, but it's not idiomatic to usemalloc
in C++. malloc is a libc function. C++ has its own standard library. C++ hasnew/delete
and constructs likestd::vector
which are explicitly designed for the purpose of dynamically allocating memory. You lose the ability to use these facilities if you attempt to have compatibility between both languages at once.