Multiple Definition and Namespace

Is this the right way to have functions in the namespace that I will include # in multiple files?

test.h

#pragma once #ifndef TEST #define TEST namespace test{ namespace { bool test(){ return true; } } } #endif //TEST 
+4
source share
3 answers

Enabling the TEST security name is likely to conflict with some other macro; use something more complex, such as HEADERNAME_H .

Note: names beginning with an underscore followed by uppercase letters and names containing two consecutive underscores are reserved for implementation.

Secondly, if you are going to put this in the header file, then the function definition must be inline . Otherwise, when you include multiple translation units, you will receive a linker error with multiple definitions. Or more formally, the standard ODR (one definition rule) prohibits such multiple definitions, unless they are inline and are virtually identical.

Edit : delete above because I have not seen the use of an anonymous namespace.

Instead of an anonymous namespace that gives you a separate namespace in each translation unit and a separate (identical) function definition in each such namespace, instead, just use inline - as explained in the crossed out text above.

Cheers and hth.,

+8
source

Anonymous namespaces make all identifiers that they wrap unique to the translation unit they are located. The inclusion of an anonymous namespace in the header, which will (sooner or later) be included in different translation units, will result in identifiers defined in this anonymous namespace, separately (but identically) in each translation unit .

I have not seen a use case where this is needed.

+2
source

Yes. Because it gives you the opportunity to call the same things the same names and just keep those names.

0
source

Source: https://habr.com/ru/post/1337456/


All Articles