Hello - I’m trying to get a firm understanding / proper use of header wrappers.
V5 Pro has a user-prog.h / user-prog.cpp file. What I gather is in the header file it should have: #ifndef USERPROG_H #define USERPROG_H
<this is where I declare all of the user variables/functions> #endif
Looking at an Arduino/Marlin config it seem they use a #define for every variable & was wondering your thoughts…
While yes, that is the proper way to do headers, because it protects against some problems with includes. Though it isn’t required to have a header file, so you should definitely write your headers like that. It’s good practice. It protects against include errors.
I recommend reading up on the header structure outside of a vex context.
the #defines are called include guards and you don’t need a unique one for each variable. Its better to use just one for the whole header, or better yet, use #pragma once
With a small project, you probably don’t even need header guards. The purpose of the guards is to stop the contents of the file being included more than once in a single source file if there’s a chance of it being included by one of the other include files, that is, if you have something like this in your code.
#include "filea.h"
#include "fileb.h"
and inside fileb.h it also had the line
#include "filea.h"
There’s no need for the pre-processor to process the file a second time as it was already included.
It does not stop the contents being included by other .cpp files you have in the project, it’s used by the preprocessor only. There’s sometimes the thought that global variables and/or function can be placed in the header and the guards will stop them being added to the project more than once, that’s not the case. You can declare global variables extern and have function prototypes, but the header should not have variable declarations and/or any actual code.
so this is ok.
extern int myVariable;
int foo( int p );
this is not
int myVariable = 9;
int foo( int p ) {
return p * 1234;
}
#pragma once is not part of the C++ standard but is widely supported now. I tend to avoid it just because it made code less portable, that is, not all compilers supported it a few years back.