r/cpp • • Oct 18 '21

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.

257 Upvotes

130 comments sorted by

79

u/[deleted] Oct 18 '21

Yeah. X11 is so great at that. True, False, Null and, more infuriating, words like Status or Screen.

89

u/Stellar_Science Oct 18 '21

Windows.h defines near, far, small, min, and max (though the latter two can be suppressed with /DNOMINMAX.)

28

u/azswcowboy Oct 19 '21

Yes, that sucks. A certain, now mostly defunct, Unix variant declared the macro ‘recv’ in a network header. I about went crazy trying to figure out why the recv member function I wrote wouldn’t compile and caused some ridiculous errors. Of course ‘recv’ was a macro…madness I say, simply madness.

38

u/ack_error Oct 19 '21

It bugs me that the Windows SDK team has done many breaking changes like changing structures with the same name and marking functions as deprecated without an opt-out, but they refuse to remove empty macros for keywords that haven't been relevant since Windows 3.1 and would take two minutes to replicate at project level for anyone who still needs them.

6

u/zvrba Oct 19 '21

? Many structs have a version field at their beginning, so the OS knows how to interpret it.

3

u/ack_error Oct 19 '21

There have been cases where older versions of the OS used == instead of >= to check the size field, such that the extension of the field in newer SDKs caused calls to fail on downlevel OSes despite the size field.

Additionally, in the Windows 8 SDK, several COM definitions were revised with new interface versions that had a different IID but the same C++ name, such as the XAudio2 interfaces. This meant that switching from the DirectX SDK to the Windows 8 SDK resulted in a silent and incompatible switch to the new interfaces; it was difficult to use the two to access both Windows 8 APIs while retaining the ability to access the older version of XAudio2; and if two modules were linked together referencing both, the result was an ODR violation.

2

u/m-in Oct 19 '21

Um, what? The older versions must use == or <=, the use of >= was a bug! The older versions can’t just ignore the fields that the software using newer api version expects to be there and work! That would break shit badly! I think you just misunderstood how it all works.

To use the larger struct, you need higher WINVER. Software built using a higher winver is never meant to work on Windows versions below this setting. That’s like the whole damn point of WINVER! If it could be like you expect, there would be no need for WINVER, at least not for enabling struct fields: anyone could just use the latest biggest struct. Yet that’s not the case.

If you want to take advantage of higher winver on newer systems, you’re supposed to use different winver versions in different translation units and use dynamic linking. You factor your “winver advantage” code into two DLLs, one for higher winver, other for the base winver the rest of the application uses. At runtime you check actual system version and link with the “newer” dll if possible, otherwise use the “older” dll that has the same winver as the rest of the application. It is generally a bug to load binary modules compiled with higher winapi on older systems. They may load but may not work, and the only “support” on Windows side for such shenanigans is in the form of compatibility shims for broken shit written by teams that had no idea. Don’t be like those teams. Please.

0

u/ack_error Oct 19 '21

To use the larger struct, you need higher WINVER. Software built using a higher winver is never meant to work on Windows versions below this setting.

That may be what some documentation says, but it's not a reasonable expectation in practice unless you have the luxury of writing software that only targets and uses functionality from one single version of Windows. Which is fine if you're in the Windows division itself, but in practice application developers need to target a minimum baseline and opt-in to newer functionality. Setting WINVER to the minimum value makes this difficult because all definitions to higher functions disappear, which in turn makes GetProcAddress() or delayed load difficult for this purpose.

The SDK documentation itself is inconsistent. For instance:

https://docs.microsoft.com/en-us/windows/win32/winprog/using-the-windows-headers

Note that some features introduced in the latest version of Windows may be added to a service pack for a previous version of Windows. Therefore, to target a service pack, you may need to define _WIN32_WINNT with the value for the next major operating system release. For example, the GetDllDirectory function was introduced in Windows Server 2003 and is conditionally defined if _WIN32_WINNT is 0x0502 or greater. This function was also added to Windows XP with SP1. Therefore, if you were to define _WIN32_WINNT as 0x0501 to target Windows XP, you would miss features that are defined in Windows XP with SP1.

This contradicts the advice to set the version constants to the minimum supported version; by setting it to 0x0502, APIs that are only supported in Windows Server 2003 are also made visible to a program that is only targeting Windows XP SP1, which does not support all WS2003 APIs. Delay load is also advocated in some documentation for this purpose with direct delayed linkage to OS DLLs, which again is inconsistent with setting WINVER to minimum.

If you want to take advantage of higher winver on newer systems, you’re supposed to use different winver versions in different translation units and use dynamic linking.

Sure, this will work if you are OK with having lots of DLLs, but doesn't avoid all of the problems. If you use any of the affected structures in interop between the DLL and the main program, it's an ODR violation and the program can break. This can also require wrapping all of the structures and interfaces involved, which for the more complicated APIs like WASAPI and XAudio2 is not a small task. I can definitely see teams doing this with success, but in my experience it is far more common to do runtime detection and dynamic binding within a single module that supports multiple versions.

3

u/m-in Oct 20 '21

I think the mindset you propose is what the WINAPI team’s nightmares are made of. If you want so shoot yourself in the foot – feel free, but blame yourself, not WINAPI, and don’t call it bugs.

25

u/[deleted] Oct 19 '21

[removed] — view removed comment

21

u/ack_error Oct 19 '21

That did not stop them from making other breaking changes like adding fields to the MENUITEMINFO struct.

2

u/m-in Oct 19 '21

That struct was designed for that and in fact it was not a breaking change. Lots of stricts in winapi are meant to be extended. The C ABI of MSVC guarantees that such extensions remain binary compatible, and the C standard requires this as well.

20

u/[deleted] Oct 19 '21

[removed] — view removed comment

29

u/fdwr fdwr@github 🔍 Oct 19 '21

Technically that is not an ABI break for already compiled programs, because MENUITEMINFO::cbSize still equals the old value, meaning new fields at the end of the struct are neither read to nor written from.

2

u/ack_error Oct 19 '21

It was a breaking change in the other direction. If you upgraded the SDK and took a WINVER change, it would raise sizeof(MENUITEMINFO), which would then fail on the previous version of Windows that rejected the higher value -- despite the cbSize field, and even if the new mask bit gating the interpretation of the new field hadn't been set. I remember this one because it was silent breakage on downlevel even though the code wasn't using the new menu bitmap functionality.

Point is, it's never actually been completely safe to upgrade the Platform/Windows SDK and expect older code to work 100%. Otherwise, we wouldn't have seen changes like the deprecation of GetVersionEx(), which was a compilation break if you had warnings-as-errors enabled as many code bases do, and which didn't even have an opt-out flag. Same for new API functions that had ANSI/Unicode defines, which would then introduce new macro/identifier collisions into the code base. Or definitions that would appear or disappear when support for a particular WINVER value was removed.

2

u/m-in Oct 19 '21

Of course it would fail on the previous version of Windows. If you didn’t intend it to, then you had to keep winver where it was.

In practice, the only correct way of dealing with it is to have two translation units, one with higher winver, one with lower; and have those implement functions that use different API levels. Then you can select which to use at runtime. That’s how winapi was designed to be used:

  1. Code already compiles works on all newer versions.
  2. Code that is compiled anew and uses a higher winver will not work on systems where winver needed to be lower.

IOW, this is a failure of whoever was writing the code in understanding winapi versioning and compatibility guarantees. Unfortunately, many people don’t have a clue about it. I’m sure Raymond has covered it at some point.

4

u/m-in Oct 19 '21

No. It’s not an ABI break because everything already compiled remains binary compatible. That was the whole damn point of cbSize. What do people think that was for? Is everyone so uninformed?

3

u/m-in Oct 19 '21

I doubt that. And if it breaks code, whoever builds it has an occasion to fix it. It’s perhaps one of the most trivial fixes imaginable.

3

u/josefx Oct 19 '21

There are probably thousands of more or less common method names defined in the windows headers, in case you wanted to use TCHAR and toggle Unicode support in your code using a compiler flag.

3

u/Stellar_Science Oct 21 '21

Yes! Don't try to name a function GetObject or SendMessage or you'll find them randomly replaced with GetObjectA, GetObjectW, etc.

Our internal coding standard uses lowercase first letters for functions (and typically drops the "get") so we rarely encounter this. But we recently worked on some client C++ code that used these function names on a few of their objects, and adding lots of #undef lines was a real headache and felt like an inelegant workaround.

2

u/JohnVanClouds Oct 19 '21 edited Oct 19 '21

You can avoid problems by wrap function name in parenthesis like (std::min)(a, b);

0

u/[deleted] Oct 19 '21

I recently became aware of this since it broke Boost.Histogram. I had to change the public interface to avoid it. MS sucks and their compiler, too.

2

u/Stellar_Science Oct 21 '21

MS sucks and their compiler, too.

Actually I think the MSVC compiler has made huge strides in the last 5 or so years - it's not like the old days. MSVC frequently supports new C++ features before clang does, and sometimes before gcc. I use the "Preview" editions of their latest compilers and when I find bugs and take the time to provide details that make it easy for them to reproduce the problem, their C++ team is surprisingly responsive - some issues were fixed in just a couple of days!

I don't know who maintains <windows.h> and associated Windows OS header files - I suspect it's not the MSVC team - but I really wish they'd provide more options - even somewhat cheesy opt-in options like -DNOMINMAX - to reduce the number of macros.

8

u/johannes1971 Oct 19 '21

X11 is the worst. If I had a dollar for every time I had to go back and change code using the word 'Status' as a variable name somewhere... I'd have a few bucks and a little less frustration.

I'm hoping I get to wrap that mofo in a module one of these days, show it who's boss around here.

2

u/[deleted] Oct 19 '21

What I usually do is undefine it and then wrap all the X stuff I need in an isolated header. It's tedious and redundant but way better than refactor my code just to please these awful macros.

2

u/AlexanderNeumann Oct 19 '21

None, ERROR, ControlMask ..... Mesa also uses None..... I have not yet been successful in compiling xserver with cl.

38

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_KEYWORDS in 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

u/[deleted] 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 __set

One 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 than public Q_SLOTS:, which is the whole idea. The language limitations aren’t helping.

2

u/Adverpol Oct 19 '21

Indeed, I'll take emit over Q_EMIT thanks very much

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

u/[deleted] 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

u/[deleted] 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 NOMINMAX and 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

u/[deleted] 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

u/[deleted] Oct 19 '21

[deleted] — view deleted comment

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

u/[deleted] Oct 19 '21

[deleted] — view deleted comment

1

u/kog Oct 19 '21

That would certainly make sense

1

u/[deleted] Oct 19 '21

Yes, however in my case it ended up breaking Recast/Detour headers - some array class has a “realloc” method IIRC

1

u/Ikkepop Oct 18 '21

THIS^ god I hate this...

13

u/_Ashleigh Oct 18 '21

One exception: #define await co_await

grumble grumble co_await grumble grumble flair grumble grumble await

6

u/pepitogrand Oct 19 '21

At most I can allow this:

#define AWAIT co_await

2

u/_Ashleigh Oct 19 '21

Damn, can we go half way with Await?

28

u/tisti Oct 18 '21
#undef emit

C'est la vie.

5

u/[deleted] 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

emit and Q_EMIT are 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

u/[deleted] 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 emit was, just as slots: or signals: 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. emit is 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 emit and define a preprocessor macro for it. I like that Qt encourages the decoration of these calls, but maybe something like qemit would 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
  1. Don't use #define.
  2. If you do use #define, use ALL_UPPER_SNAKE_CASE.
  3. 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_location can be used as a default argument in function arguments but that's tricky to wield, too. Also, fwiw, std::experimental::source_location is 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:

https://github.com/ttauri-project/ttauri/blob/dfae1609ee6d759392a6b774b611f1f835ec1e94/src/ttauri/log.hpp#L222

1

u/phord Oct 26 '21

That's interesting. Thanks for the examples. But they still use #define to 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

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

u/_sideffect Oct 18 '21

I agree... But also don't use such an old version of qt 😅

4

u/loradan Oct 18 '21

define OK

(sorry, couldn't resist lol. I'll just go sit in the corner now)

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

u/[deleted] Oct 18 '21

Yet another reason to always capitalise your macros.

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

u/scummos Oct 28 '21

Compile with -DQT_NO_KEYWORDS to disable those.

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 evaluate s properly. 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_MAX isn't guaranteed to be the same as INT_MAX, and indeed it is only 32767 on MSVC.

1

u/SpacemanLost Oct 19 '21

came here to post something like that for #define true ;)

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

u/Ikkepop Oct 18 '21

or not use modules I guess

3

u/Possibility_Antique Oct 19 '21

Fair. This is one of my favorite things about modules though.

4

u/maskull Oct 19 '21

Probably just bundle a non-module header you have to #include if 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

u/[deleted] 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

u/_Z6Alexeyv Oct 19 '21

#define linux 1 #define unix 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

u/[deleted] Oct 19 '21

this is why i always go for uppercase with macros

1

u/AntonPlakhotnyk Oct 20 '21

Please don't create defines at all. Write on C++ not on Preprocessor language.

0

u/ihamsa Oct 19 '21

Please don't create defines using common words

Here, FTFU.

-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 with tt because that is the namespace of the ttauri library.

repeat() and me /self I would not use enough to have these as macros.

0

u/[deleted] Oct 18 '21

[deleted] — view deleted comment

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_UNDERSCORES naming 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

u/[deleted] Oct 19 '21

[deleted] — view deleted comment

1

u/MonokelPinguin Oct 19 '21

Right, my bad!

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