For example, I have a markerdisplay.cpp file. The markerdisplay member function will look like the below code.
void MarkerDisplay::setMarkerStatus(MarkerID id, StatusLevel level, const std::string& text)
{
.....
}
Can I have a non-member function in the markerdisplay.cpp?
For example,
bool validateFloats(const visualization_msgs::Marker& msg)
{
...
}
The function validateFloats is not a member function, and I also don't declare it in the header file. I only use this function inside of the validateFloats.cpp file.
Someone told me this may cause some problems. Is that true?
No, it is not necessary. The reason of the header files is to separate the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the .
Function declarations are mandatory in C. Prototypes, however, are optional, except in the cases of variadic functions and functions whose argument types would be altered by default promotions.
It is always recommended to declare a function before its use so that we don't see any surprises when the program is run (See this for more details).
header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.
If you don't need the function outside of the .cpp
, it is sufficient to declare and define it in that file. Of course you will still have to declare it before first use, but that is the only "problem" I can think of.
It is rather a good idea not to declare the function in the header if not needed because you use up fewer "project-public" names and make it easier to find all uses of the function, thus making the code more maintainable.
If you don't declare the function in your header, you should make it static
:
static bool validateFloats(const visualization_msgs::Marker& msg);
or put it in an anonymous namespace:
namespace {
bool validateFloats(const visualization_msgs::Marker& msg);
}
(preferred) to avoid accidental cross-translation-unit name clashes.
my question is: can I have non member function in the markerdisplay.cpp for example ...
Yes, you can do that.
The best choice would be to provide that function in the implementing translation unit if it's not intended to be used from the public API.
You can even completely hide that (including the linker) in an anonymous namespace
namespace {
bool validateFloats(const visualization_msgs::Marker& msg) {
// ...
}
}
Alternatively just defining a static
function in the translation unit should have the same effect:
static bool validateFloats(const visualization_msgs::Marker& msg) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With