Rant: please don't create defines using common words
Looks like QtCore (4.8) has a "#define emit" in a header, that's not undefined later. TBB has a function named "emit()" in a header. If you include both, you'll get a compile error.
I'm going to side with TBB here - emit() is an entirely reasonable function name. Qt creating a dangling #define with a common word like that is the bug here.
39
u/o11c int main = 12828721; Oct 18 '21
Zlib is the worst:
For a brief while, it had #define ON in addition to the (much less dangerous) #define OF [sic, not OFF - it stands for "function"].
Obviously the ON broke things, but the patch also changed OF.
Turns out I broke half of Gentoo, since there are a lot of projects out there that embed copies of zlib but still use the system header.
People: PLEASE do not vendor your dependencies. Installation exists for a reason.
19
u/chrisoboe Oct 18 '21
Turns out I broke half of Gentoo, since there are a lot of projects out there that embed copies of zlib but still use the system header.
So you didn't broke half of gentoo but the projects were already broken, since they embed copies of zlib but still use the system header.
19
u/ApproximateArmadillo Oct 18 '21
English as second language and c++ novice here. Could you define what "vendor" and "installation" mean in this context please?
20
u/MonokelPinguin Oct 18 '21
"vendor" as in "vendoring dependencies" means shipping common libraries in your source tree. For example putting zlib into a subfolder of your git project and using that instead of the one provided by your operating system.
12
u/ReversedGif Oct 19 '21
People: PLEASE do not vendor your dependencies. Installation exists for a reason.
Why, exactly? The story you gave is only a reason to not "half-vendor" dependencies, which is obviously dumb and broken.
4
u/o11c int main = 12828721; Oct 19 '21
If it's a library that anybody else uses, vendoring at all means it's almost impossible to avoid half-vendoring one way or another. Includes is only one possibility; runtime symbols are another.
Particularly, it is very easy to end up with two different versions of the same library linked into a program.
The only practical solution is not to vendor at all. (giving the correct arguments to ld or ld.so can fix this in theory, but I think I've only seen one program ever do this, and that wasn't actually vendoring)
7
u/SirClueless Oct 18 '21
I'm confused, what patch exactly did you make and how did it break Gentoo? You're saying you changed a system header and then Gentoo builds broke? Wouldn't that happen regardless of whether they vendored zlib?
29
u/brenoguim Oct 18 '21
Also "signal" is a very valid variable name. However qt also defines that.
18
u/EmperorArthur Oct 18 '21
it's really annoying that some major libraries don't bother to use namespaces, or at least a macro equivalent.
8
u/m-in Oct 19 '21
They do, or at least Qt does. You can disable non-namespaced macros : just define
QT_NO_KEYWORDSin your project, or at the top of every translation unit before any Qt headers get included.17
u/disperso Oct 19 '21
It's conditionally defined, though. CONFIG+=no_keywords and problem solved.
2
Oct 19 '21
/u/patery, this is your answer right here.
1
u/trvlng_ging Oct 19 '21
I disagree. The default should be to NOT uave identifiers that aren't scoped to a namespace. Require explicit action to do harmful stuff.
23
u/bro_can_u_even_carve Oct 19 '21
My favorite was when some terrible STL implementation (HP, I think? Or maybe Sun... this was almost 20 years ago) did something like this...
#define map __map
#define set __setOne unfortunate day I added a simple `void set(...);' method declaration to the wrong class, and was greeted with an incomprehensible error message. Imagine the look on my face when I finally tracked down the cause.
106
u/wung Oct 18 '21
If you're using qmake: CONFIG += no_keywords and it won't define emit but only Q_EMIT.
If you're using a different build system generator, define QT_NO_KEYWORDS with the same effect.
emit being "dangling" is intentional. That's an API. You "can't" use Qt without slots: and emit.
39
u/DarkLordAzrael Oct 18 '21
Actually, emit does literally nothing. It is there to call out a specific type of function call, but it never impacts behavior and is completely optional.
6
u/wung Oct 19 '21
I am well aware, but signals and slots does. Defining one keyword less doesn’t change the original complaint.
30
u/HolyGarbage Oct 18 '21
Sure, but an API is typically protected against conflicts with a namespace, or in c with a unique prefix. Not using either is just sloppy and careless.
10
u/AntiProtonBoy Oct 18 '21
Yeah and in the case of Qt, they could've just use to extra letters for the prefix. Three if you want an underscore as well.
6
u/wung Oct 19 '21
And they do, as evidenced by the option to only expose the prefixed macro. Not prefixing it and making it short and keyword-looking is intentional:
public slots:feels more natural/like a language extension thanpublic Q_SLOTS:, which is the whole idea. The language limitations aren’t helping.2
57
u/JohnDuffy78 Oct 18 '21
win.h bastards #define min / #define max. Worse, they won't take it out.
Another issue is with a 3rd party library #define assert, should be left to os headers.
32
u/SkoomaDentist Antimodern C++, Embedded, Audio Oct 18 '21
win.h bastards #define min / #define max. Worse, they won't take it out.
To be fair, those defines predate even the original C standard, nevermind C++.
24
u/donalmacc Game Developer Oct 18 '21
#define nominmax
6
Oct 19 '21
The issue is when writing libraries with headers that use min/max. One generally cannot force compile flags on users, as much as people try. So one gets to see (std::min)( a, b )
4
u/donalmacc Game Developer Oct 19 '21
Windows.h defining min and max is definitely a pain, dont get me wrong but it's got a very simple, well documented workaround, and their legacy choice likely predates whatever library youre using. As a library writer you have multiple choices
let the user deal with it
wrap your headers in #ifndef NOMINMAX
call std::min explicitly
I don't really think minmax is worth complaining about these days.
1
Oct 19 '21
It pretty much has to be the user, otherwise one can get ODR issues. One can lower the number of issues the user experiences though.
1
u/m-in Oct 19 '21
Parenthesizing to suppress macro expansion is an everyday thing :) I mean, they made it work that way for a reason. It wasn’t a coincidence that it’s done that way.
9
u/ajorians Oct 18 '21
Though it has bothered me as well; just in case you didn't know you can make a preprocessor define of
NOMINMAXand it won't define min/max. You would need to do that for pretty much for every project in your solution. It isn't perfect as GDIPlus won't compile without those macros defined, as an example. Here is a screenshot from windows.h: https://www.screencast.com/t/C3TG5ugN88l showing this preprocessor define as well as some others. Hope that helps!3
u/Supadoplex Oct 19 '21
Note that this is a common problem with system headers; not solely on windows. Linux, BSD etc. define a lot of non-reserved and even non-capital macros in their headers.
2
u/m-in Oct 19 '21
If you don’t use std min/max too often in C++, you just should use fully qualified name and parenthesize it: the macro won’t be used!
E.g. this works without NOMINMAX:
(std::min)(42, 142). It doesn’t work without parentheses, ie.std::min(a,b)won’t work.Basically, as long as you manage to get a symbol declared without interference from
Windows.h, to use it just stick it in parentheses. It suppresses macro substitution.4
Oct 18 '21
crtdbg.h #defines malloc, calloc, realloc, and free by default.
9
u/OldWolf2 Oct 18 '21
The standard allows for standard library functions to be defined as macros
0
Oct 19 '21
[deleted]
3
u/JMBourguet Oct 19 '21
IIRC C allows any functions to be defined as macro, C++ does not excepted in specific cases, I don't remember if there is a blanket allowance for the one originating in C, but don't think so.
0
Oct 19 '21
[deleted]
1
1
Oct 19 '21
Yes, however in my case it ended up breaking Recast/Detour headers - some array class has a “realloc” method IIRC
1
13
u/_Ashleigh Oct 18 '21
One exception: #define await co_await
grumble grumble co_await grumble grumble flair grumble grumble await
6
28
u/tisti Oct 18 '21
#undef emitC'est la vie.
5
Oct 18 '21
until you want to emit something later.
Doesn't even make sense they have it because as far as I know emit is a keyword used by the qt preprocessor.
3
u/m-in Oct 19 '21
emitandQ_EMITare not used by any preprocessor. They are human readable keywords that document emission of a signal and make it more obvious, since signal emission can have interesting side effects in code written without understanding (like filling up event queues and some quadratic event queue behavior). It’s important to know where signals are emitted when you skim the code, and a custom keyword does this job admirably, and kudos to Qt team for choosing a keyword and making its use a matter of practice even when people don’t quite get what it’s for. It has been an option for a long time to disable the non-namespaces keywords, and also to put Qt into a namespace. You can do the keyword disabling when building Qt, and then it becomes “entrenched” and automatic. Otherwise, you add the macro definition to your project’s build options. Easy.1
Oct 19 '21
Don't get me wrong, I have nothing against the usage of the MOC. In fact it is a great solution for Qt and makes things a lot easier for the purposed domain.
I was just under the wrong assumption that
emitwas, just asslots:orsignals:a keyword stripped by the MOC to hide away event propagation details and if that was true there wouldn't be any reason for a macro.Now, according to this and this it is true what you say.
emitis in fact an empty macro that only acts as a marker for a place in code where magic stuff kicks in (because of the auto-generated signal implementation) and you can disable it if you don't want it.But from another point of view this is global namespace pollution. You take such a generic, commonly used word as
emitand define a preprocessor macro for it. I like that Qt encourages the decoration of these calls, but maybe something likeqemitwould have been less painful.1
u/m-in Oct 20 '21
Personally I find the Q_SLOTS and Q_SIGNALS a bit cumbersome. I like grouping method declarations in functionally related groups, and in those cases each signal and slot is individually annotated with Q_SIGNAL and Q_SLOT. It looks less alien to most developers too, since everyone is familiar with similar annotations for calling convention, symbol visibility, and other attributes.
1
u/disperso Oct 19 '21
emit is empty and does nothing. Is purely informational or stylistic. And it's conditionally defined, unlike Q_EMIT.
18
u/phord Oct 19 '21
Don't use
#define.If you do use #define, use
ALL_UPPER_SNAKE_CASE.For everything else, there's
namespaces.
13
u/bikki420 Oct 19 '21
4. Prefix it with your library/project abbreviation (preferably the same as your core namespace, except all uppercase).
0
u/tjientavara HikoWorks developer Oct 19 '21
I prefix with my library's namespace, but I use lower case for function-like and keyword-like macros.
2
u/Wouter-van-Ooijen Oct 20 '21
Please don't.
Either don't use such constructs (who needs function-like macro's?), undef them at the end of your header, or - as a last resort - make them all UPPERCASE (and prefixed). The main reason it that macro's don't play nice with scope and re-use of the same word (even within another scope).
1
u/tjientavara HikoWorks developer Oct 20 '21
You need function-like macros for logging/asserts/compiler-specific-keywords.
I prefix the namespace in front of the macro name exactly to reduce the chance of name collision.
2
u/Wouter-van-Ooijen Oct 20 '21
Good to prefix. I admit that logging might be one of the niches for macros. (Although with the C++20 source location...?)
But why not CAPITALIZE?
1
u/tjientavara HikoWorks developer Oct 20 '21
source_location can't be used as non-type template arguments.
Using source_location would slow down logging relatively significantly in my implementation, so I will keep using __LINE__ and __FILE__.
I like to use snake_case for functions and variables like the std library. Also many intel intrinsics are lower case macros.
1
u/Wouter-van-Ooijen Oct 20 '21
This is of course all opinion.
IMO intel intrinsics would be known to all users of that tool, but your lib would be a maybe-sometimes use. So better make everything that isn't a normal identifier stand out.
1
u/phord Oct 21 '21
That is disappointing about source_location not fitting into template args. But I'm not sure it would help because constructor args are filled where the template is declared.
source_locationcan be used as a default argument in function arguments but that's tricky to wield, too. Also, fwiw,std::experimental::source_locationis available in c++17.I doubt either one would significantly slow down your logging as they likely get optimized down to the same code as using
__LINE__and__FILE__in the end.1
u/tjientavara HikoWorks developer Oct 21 '21
__LINE__ and __FILE__ can be used as template arguments, therefor you can due value-erasure (like type-erasure but with values).
So when logging the __FILE__ and __LINE__ are part of the class that is added to the ring buffer, and is accessed through the vtable-pointer that is written to the ring buffer already to handle the type-erasure of the std::format arguments.
In case you are wondering c++20 allows for fixed_string template arguments.
Here are the tt_log_* macros that use __FILE__ and __LINE__ as template arguments:
1
u/phord Oct 26 '21
That's interesting. Thanks for the examples. But they still use
#defineto pick up the unique__LINE__and__FILE__values. I'm pretty sure this is necessary since the preprocessor handles the expansion of those, but templates are resolved later by the compiler.→ More replies (0)
9
u/victotronics Oct 18 '21
I once spent the best part of a day debugging a `#define map` occurring in some header.
15
u/Dean_Roddey Oct 18 '21
That ship already sailed pretty much. Anyone on Windows has probably gotten screwed at some point with defines in the Windows SDK headers. Looking back with 20/20 vision, not requiring a special syntax to expand a macro is one of the biggest blunders in C/C++ history.
Even scarier is that everything could conceivably compile in your whole code base and all tests work (because the same define changed the same thing everywhere) but then your customers or users get missing identifiers.
2
u/Disastrous-Jaguar541 Oct 19 '21
No. The biggest blunder is not to write your macros with a uniform syntax requiring ALL_LETTERS_IN_UPPER_CASE.
7
u/ack_error Oct 19 '21
This seems common for projects that initially started as just application code and then became a framework once they had grown large. It can be a pretty nasty hole to climb out of. The framework I'm currently using has macros like check() and ensure(), which are endemic at this point. They're starting to try to fix the problem with appropriate prefixing, but it's amusing to receive a compiler warning after an upgrade that the DEPRECATED macro has been deprecated.
8
4
4
u/madmongo38 Oct 19 '21
Qt also defines the macro signal, which is probably the most antisocial thing I've seen a library do.
7
u/ThisCleverName Oct 18 '21
I don't think is something new. Q_EMIT is used in those cases. I believe there is a define so Qt doesn't use those things as keywords
3
u/Clairvoire Oct 19 '21
If I find a define like that, it's a no-go on that library unless I can undef it, same goes with min max near far etc
3
u/GLIBG10B 🐧 Gentoo salesman🐧 Oct 19 '21 edited Oct 21 '21
Try to avoid defines as much as possible. Use constexpr where applicable.
4
2
u/Supadoplex Oct 19 '21 edited Oct 19 '21
If you can avoid it, don't define a macro at all. Or at least undefine it after use. And when neither is possible, follow the ubiquitous convention of using only upper case chars, and prefix with a "namespace".
2
u/goranlepuz Oct 19 '21
emit() is an entirely reasonable function name
Ehhh... Not so much in a supposedly widely used library.
I agree that Qt is worse, but it is so much more a case of who is more wrong, than who is right.
2
5
u/sudomatrix Oct 18 '21 edited Oct 18 '21
Could be worse
#define if(s) if(s && std::rand() > RAND_MAX*.05)
6
u/psychob Oct 18 '21
rand()will never return decimal number, hence your code will always evaluatesproperly. What you wanted is probably:#define if(x) if ((x) && rand() <= (INT_MAX) - 2)7
u/louiswins Oct 19 '21
It looks like OP has edited theirs to be correct. Yours may work depending on the platform:
RAND_MAXisn't guaranteed to be the same asINT_MAX, and indeed it is only 32767 on MSVC.1
2
u/Ikkepop Oct 18 '21
I would like to shorten this thought to : "please don't create defines"
2
u/OldWolf2 Oct 18 '21
Modules might help with this, since macros can't be exported in modules so people will have to come up with other ways to do what they're doing with the macros currently.
5
4
u/maskull Oct 19 '21
Probably just bundle a non-module header you have to
#includeif you want the macro definitions. I'm working on a library right now which would basically be unusable without a few judicious macro definitions (all of which are prefixed by the name of the library, of course).
1
1
Oct 19 '21
Instances where the framework decides for you, +1.
2
u/disperso Oct 19 '21
Not really, it's just an opt out feature. You can always use Q_EMIT and QT_NO_KEWORDS.
1
1
u/rysto32 Oct 19 '21
Related rant: if it's been established practice in several operating systems to have some constants defined as macros, do not reuse the names as your own static const variables!
e.g. If OS headers have this:
#define EI_MAG0 0
For the love of god, don't put this in your library's headers:
static const int EI_MAG0 = 0;
or this:
enum { EI_MAG0 = 0, };
1
u/Zcool31 Oct 19 '21
Ever try to use Unix domain sockets on Solaris?
sockaddr_un sun;That isn't the sun you're looking for.
1
1
u/AntonPlakhotnyk Oct 20 '21
Please don't create defines at all. Write on C++ not on Preprocessor language.
0
-1
u/john_wind Oct 19 '21
There are some common words which I really like to #define
#define me (*this)
#define repeat(n) for (int i=0; i<int(n); ++i)
#define let const auto
2
u/tjientavara HikoWorks developer Oct 19 '21
My library ttauri, uses
#define ttlet auto const. I prefixed it withttbecause that is the namespace of the ttauri library.
repeat()andme/selfI would not use enough to have these as macros.
0
Oct 18 '21
[deleted]
9
u/pepitogrand Oct 19 '21
Polluting the global namespace is evil, at the very least those identifiers should be in uppercase and with a QT_ prefix.
8
u/apadin1 Oct 18 '21
Exactly, this wouldn't be a problem except that macros are global and can't be limited to a namespace. I understand macros have their uses, but in that case they should be #undef'd at the end of the file so they don't affect other files
5
u/gravitatingmass Oct 18 '21
I would avoid making generalizations like this. There have been numerous times in production code where I've found macros to be the only way to do something, e.g., code gen. or, at least, much more convenient.
I don't think there are any "evil" language features, but they can certainly be used in evil ways.
But I agree that Qt's particular use of macros like is pretty evil.
6
u/Stellar_Science Oct 18 '21
Agreed, macros are not evil but they are ugly - our coding standard is basically "macros are ugly so they should look ugly." An
ALL_CAPS_VERY_LONG_WITH_UNDERSCORESnaming convention helps minimize the odds of macros clashing between libraries.10
u/MutantSheepdog Oct 18 '21
I think this is generally accepted and if QtCore had have gone with QT_EMIT they would have saved OP some headaches.
I'm hoping one day (once we have things like reflection) we can retire preprocessor macros entirely and use language-level features with proper scoping, but for now macros are still sometimes the best tool for the job.
3
u/MonokelPinguin Oct 18 '21 edited Oct 19 '21
You can use Q_EMIT instead by defining QT_NO_KEYWORDS or just don't use anything at all. The emit is just there to make signals stand out more and code more readable, but it is completely optional and does literally nothing. I find Q_EMIT much harder to read and it takes only a few minutes to figure out the issue usually and it is easy to fix.
0
1
u/EmperorArthur Oct 18 '21
One of the advantages of modules at least is that it limits the impact of these types of things.
4
u/MutantSheepdog Oct 18 '21
Yeah modules do help ensure macros aren't accidentally leaked, but in cases like this one I'm assuming the macro is part of the public API so unless modules ever change to let us explicitly export and rebind macros, they can't really help.
It would be nice if modules could do something like this though:
#export emit as QT_EMIT
79
u/[deleted] Oct 18 '21
Yeah. X11 is so great at that. True, False, Null and, more infuriating, words like Status or Screen.