C ++ enable guards don't seem to work

I get error messages from the C ++ mbed compiler, which seem to indicate a malfunction, include security devices.

In main.cpp, I include the header file as follows:

#include "mbed.h" #include "sample.h" 

This is my .h example:

 #include "mbed.h" #ifndef STUFF_H #define STUFF_H /* LEDs */ DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); DigitalOut led4(LED4); /* Subroutines */ void sweepLEDs(); void pulseLEDs(int numPulses); void clearLEDs(); #endif 

In sample.cpp, I include sample.h as follows:

 #include "sample.h" 

In the main.cpp and sample.cpp files, I mean the variables led1, led2, led3, led4 , without declaring them. However, the compiler outputs these complaints:

"The led1 symbol is propagated (following the pattern .cpp.cpp.LPC1768.o and main.cpp.cpp.LPC1768.o)." ... Msgstr "The led4 symbol is repeatedly defined (using sample.cpp.cpp.LPC1768.o and main.cpp.cpp.LPC1768.o).

Can my guards write incorrectly? Or is there another problem?

(For reference: source link mbed.h )

+3
source share
2 answers

The problem is a misunderstanding of what the guards include. Turn on protective measures so that the compiler does not see the same content again in the same translation system (for the same .cpp file). They do not prevent individual translation units from seeing the same code.

In your header file, you define (not just declare) variables. Therefore, each translation unit that includes a heading creates its own copy of these variables.

The correct way to do this is to define the variables in the .cpp file and only declare them in the header (in any case, protective measures must be present to prevent multiple inclusion in the same block of translations).

That is, in your sample.h file, prefix your variables with extern and remove the initializer (so that they are declared, not defined) and define them in the corresponding .cpp file (where the functions are also defined), putting the exact definitions from your header there .

In an unrelated note, you should put #include "mbed.h" in sample.h inside the included guards, because some compilers optimize compilation speed for such guards and that optimization does not work if there is material outside the included guards. Please note that this is not a correctness problem (assuming that mbed.h is also correctly protected by the included guards), but a performance compilation problem.

+12
source

You need to mark the declarations as " extern " as follows:

 extern DigitalOut led1; 

Then define them (i.e. allocate storage for them) in sample.cpp using the expression you used in the header.

+4
source

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


All Articles