C++ Namespace around header declaration and source definition - c++

I am making a static library, everything defined in it is all in one namespace. But I am unsure whether I should define the methods as if you would a class, or also wrap them in the namespace. What I'm asking is:
Is this valid:
MyThings.h
namespace MyThings {
void DoStuff();
void DoOtherStuff();
}
MyThings.cpp
namespace MyThings {
void DoStuff() {
// Do this.
}
void DoOtherStuff() {
// Do that.
}
}
Or, should I define it like I would class methods?:
MyThings.cpp
void MyThings::DoStuff() {
// Do this.
}
void MyThings::DoOtherStuff() {
// Do that.
}
I would prefer not to use using namespace MyThings;, and I would prefer to use my first example if it is valid, I feel it makes the code more readable without having to use MyThings:: before every method identifier.

Both are valid, so you can pick your style according to taste.
There is an advertised advantage of defining the function using:
void MyThings::DoStuff() {
// Do this.
}
which is that in order to do it, the function must have already been declared. Thus, errors like:
void MyThings::DoStuf() {
// Do this.
}
or
void MyThings::DoStuff(int i) {
// Do this.
}
are caught when you compile MyThings.cpp. If you define
namespace MyThings {
void DoStuff(int i) {
// Do this.
}
}
then you generally won't get an error until someone in another source file tries to call the function, and the linker complains. Obviously if your testing is non-rubbish you'll catch the error one way or another, but sooner is often better and you might get a better error message out of the compiler than the linker.

Related

C++ Compile time check if a function called before another one

Lets say I have a class with two member functions.
class Dummy {
public:
void procedure_1();
void procedure_2();
};
At compile time, I want to be sure that, procedure_1 is called before procedure_2. What is the correct way do implement this?
Maybe you could do it with a proxy-class. The idea is, that procedure_2 can't be accessed directly from outside (for example by making it private). procedure_1 would return some kind of proxy that allows the access to procedure_2.
Some code below, allthough I don't consider it clean or safe. And if you want, you can still break the system.
IMO such requirements should be handled without explicit validation, because it's quite cumbersome and impossible to make it absolutely safe.
Instead, the dependency should be well documented, which also seems idiomatic in C++. You get a warning that bad things might happen if a function is used incorrectly, but nothing prevents you from shooting your own leg.
class Dummy {
private:
void procedure_2() { }
class DummyProxy
{
private:
Dummy *parent; // Maybe use something safer here
public:
DummyProxy(Dummy *parent): parent(parent) {}
void procedure_2() { this->parent->procedure_2(); }
};
public:
[[nodiscard]] DummyProxy procedure_1() {
return DummyProxy{this};
}
};
int main()
{
Dummy d;
// d.procedure_2(); error: private within this context
auto proxy = d.procedure_1(); // You need to get the proxy first
proxy.procedure_2(); // Then
// But you can still break the system:
Dummy d2;
decltype(d2.procedure_1()) x(&d2); // only decltype, function is not actually called
d2.procedure_2(); // ooops, procedure_1 wasn't called for d2
}
Instead of "checking" it, just do not allow it. Do not expose an interface that allows to call it in any other way. Expose an interface that allows to only call it in specified order. For example:
// library.c
class Dummy {
private:
void procedure_1();
void procedure_2();
public:
void call_Dummy_prodedure_1_then_something_then_produre_2(std::function<void()> f){
procedure_1();
f();
procedure_2();
}
};
You could also make procedure_2 be called from destructor and procedure_1 from a constructor.
#include <memory>
struct Dummy {
private:
void procedure_1();
void procedure_2();
public:
struct Procedures {
Dummy& d;
Procedures(Dummy& d) : d(d) { d.procedure_1(); }
~Procedures() { d.procedure_2(); }
};
// just a simple example with unique_ptr
std::unique_ptr<Dummy::Procedures> call_Dummy_prodedure_1_then_produre_2(){
return std::make_unique<Dummy::Procedures>(*this);
}
};
int main() {
Dummy d;
auto call = d.call_Dummy_prodedure_1_then_produre_2();
call.reset(); // yay!
}
The above are methods that will make sure that inside one translation unit the calls will be ordered. To check between multiple source files, generate the final executable, then write a tool that will go through the generated assembly and if there are two or more calls to that call_Dummy_prodedure_1_then_produre_2 function that tool will error. For that, additional work is needed to make sure that call_Dummy_prodedure_1_then_produre_2 can't be optimized by the compiler.
But you could create a header that could only be included by one translation unit:
// dummy.h
int some_global_variable_with_initialization = 0;
struct Dummy {
....
};
and expose the interface from above into Dummy or add only the wrapper declaration in that library. That way, if multiple souce files include dummy.h, linker will error with multiple definitions error.
As for checking, you can make prodedure_1 and procedure_2 some macros that will expand to something that can't be optimized by the compiler with some mark, like assembly comment. Then you may go through generated executable with a custom tool that will check that the call to prodedure_1 comes before procedure_2.

How would you cleanly follow the Stepdown rule in C/C++?

The Stepdown rule encourages to read the code like a top-down narrative. It suggests every class/function to be followed by those at the next level of abstraction so we can read the code descending in the level of abstraction.
In C/C++ you need to declare classes/functions before you use them. So how would cleanly apply the Stepdown rule here? What are some pros and cons of the following approach? Any better one?
void makeBreakfast();
void addEggs();
void cook();
void serve();
int main()
{
makeBreakfast();
}
void makeBreakfast()
{
addEggs();
cook();
serve();
}
void addEggs()
{
// Add eggs.
}
void cook()
{
// Cook.
}
void serve()
{
// Serve.
}
My approach is like yours but with either making a class so the declaration can come after use, or put declarations in a header file.

How can I call non-existent functions in C++

So, I want to know how I can call functions from header...
To explain it better, I have a header file, which is something similar to a game library.
I want to call certain functions in the Main part of the program(the dynamic one), but I want these functions not to be required.
So, if I click a hotkey combo, I'd call a function in Main part of the program called "hotkeyHit", but first I need to check if it's there. I'm implementing some kind of an "Event system".
And that's where I hit the wall...
First of all I don't know how to check if there is that function in the Main, I can't compile if there is no function called that and last of all, I can't declare the same function for second time, which leaves me with no obvious options.
So now I'd like to know how I can do that so it would work the way I want it to.
Thanks in advance
Some example clode below to hopefully explain my comment. In this, the methods in the CBaseHandler class are intentionally empty. Your Event Handler takes a reference to a CBaseHandler and in this example tries to handle a keypress and a mouseclick. However, the concrete implementation of the handler, CHandler only implements the Keypress handler (in this case just by printing a string, but you can do whatever you want)
When the Event Handler runs, only the Keypress will do anything. Presumably you'll be wanting to call that in a loop of some description in real life.
The event handler loop in your library can now take any implementation of an event handler for whatever purposes you need.
#include <iostream>
class CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
}
virtual void handleMouseClick(int i)
{
}
};
class CHandler : public CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
std::cout << "Derived - KP" << std::endl;
}
};
void DoHandle(CBaseHandler& handler)
{
handler.handleKeyPress(4);
handler.handleMouseClick(0);
}
int main() {
CHandler myhandler;
DoHandle(myhandler);
}
If you have a function declared in header file but not defined anywhere, this will compile fine. However if you attempt to use this function anywhere in the code, the linker will complain when you try to compile it as it won't be able to find the definition. So you could simply add dummy definition which does nothing.
header.h
void myFunction();
source.cpp (1)
int main()
{
myFunction(); // linker error on compile
return 0;
}
source.cpp (2)
void myFunction() {}; // dummy definition
int main()
{
myFunction(); // no problem
return 0;
}
Ok, so after getting some help from you guys and figuring it out online, I've found a solution that works for me.
I've set it up like so:
Main code:
void mouseClicked();
void main(){
setMouseClicked(mouseClicked);
}
void mouseClicked();
Header code:
void (*mc)() = NULL;
void setMouseClicked(void (*fun)(void)){
mc = fun;
}
and then in the event function I do this:
void handleMousePress(int button, int state, int x, int y){
mouseX = x;
mouseY = y;
mouseButton = button;
if(state == GLUT_DOWN){
if(mc != NULL)
(*mc)();
}
}
I've worked on a compromise by having a declaration of the function in the main part of the code and having a setter for that function, but with that I've added an ability for renaming functions that are called when the event is triggered.
So once again, thanks for your suggestions, but at the end I've found that pointers to functions work the best.

Private namespace in source files

I have a doubt regarding private methods & functions.
Let's say I have some utility methods that needn't be inside a class. But those same methods need to call other ones that I don't want to expose to the user. For example:
Suspect.h
namespace Suspect {
/**
* \brief This should do this and that and more funny things.
*/
void VerbalKint(void); // This is for you to use
}
Suspect.cpp
namespace Suspect {
namespace Surprise {
/**
* \brief The user doesn't need to be aware of this, as long
* the public available VerbalKint does what it should do.
*/
void KeyserSoze(void) {
// Whatever
}
} // end Surprise
void VerbalKint(void) {
Surprise::KeyserSoze();
}
}
So, this layout works. When including the Suspect.h, only VerbalKint is visible.
This can be as well achieved using a class and marking VerbalKint as static:
class Suspect {
public:
// Whatever
static void VerbalKint(void);
private:
static void KeyserSoze(void);
};
I would like to know if there's any difference between the two approaches. Is one better (faster, easier to maintain) than the other?
What are your thoughts?
If the functions are 'free', you should use an anonymous namespace in the *.cpp:
namespace Suspect {
namespace Surprise {
namespace {
void KeyserSoze(void) {
// Whatever
}
} // end anon
} // end Surprise
} // end Suspect
or even:
namespace {
void KeyserSoze(void) {
// Whatever
}
} // end anon
This keeps it away from clients so they cannot access, depend on, or collide with your exports when linking. It also keeps unnecessary declarations from them, reducing their compile times and potentially link times or binary sizes if definitions are visible. Finally, it makes it private so they cannot depend on it and you do not need to maintain it for their use. You can still pass these to the outside world, if you choose (function pointer in KeyserSoze()'s case).
At other times, it is preferable to declare a private member function in your class then define it in the *.cpp (where possible). Typically, you would opt for this approach when you need a closer relationship with the class (e.g. when you need access to some members). You said this was not the case in the question, but I'm just reiterating when private members should be used.
The best approach is to define all helper functions in an unnamed namespace in Suspect.cpp, instead of in the Suspect::Surprise namespace.
In your case, this would be:
namespace{
void KeyserSoze(){ ... };
}
You can simply call KeyserSoze without any namespace specifiers from within Suspect.cpp.
You can find more information about that here: Unnamed/anonymous namespaces vs. static functions
Another alternative is to declare KeyserSoze to be static, but this is not advised by the standard. The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative
Actually, even though the function is not visible to the eye when you do not declare it in any header; it still is available to the user should they write the declaration.
In C++, the mechanism to hide symbols declared at file level is:
static for (global) variables and functions
namespace { ... } (anonymous namespaces) for anything you wish (more general, more verbose)
For example:
// Suspect.cpp
namespace Suspect {
static void KeyserSore() {}
void VerbalKing() { KeyserSore(); }
}
The main difference between putting something in a class or a namespace is that you can't add extra static functions to a class in another header file.
This:
a.h
namespace Fred {
void Somefunc();
}
b.h
namespace Fred {
void Anotherfunc();
}
work, although neither a nor b know what each other has done to their namespaces. This could conceivably cause problems, such as this:
c.h
namespace Fred {
void Thirdfunc();
}
d.h
namespace Fred {
bool Thirdfunc();
}
which is all fine and dandy until you get to run the program...
This is, whilst not impossible, a lot less likely with classes.
In your example, with only one source file, you might also want to consider using the anonymous namespace as that restricts declarations to file scope, so people outside your file can't access them (or clash with them) by accident.

Function Call Guard

Suppose I have a free function called InitFoo. I'd like to protect this function from being called multiple times by accident. Without much thought I wrote the following:
void InitFoo()
{
{
static bool flag = false;
if(flag) return;
flag = true;
}
//Actual code goes here.
}
This looks like a big wart, though. InitFoo does not need to preserve any other state information. Can someone suggest a way to accomplish the same goal without the ugliness?
Macros don't count, of course.
You can do it with some different ugliness:
struct InitFoo
{
InitFoo()
{
// one-time code goes here
}
};
void Foo()
{
static InitFoo i;
}
You're still using static, but now you don't need to do your own flag checking - static already puts in a flag and a check for it, so it only constructs i once.
Well, a constructor is only automatically called once. If you create a single instance of this class:
class Foo
{
public:
Foo(void)
{
// do stuff
}
}
Then //do stuff will only execute once. The only way to execute it twice is to create another instance of the class.
You can prevent this by using a Singleton. In effect, //do stuff can only possibly be called once.
I'd like to protect this function from being called multiple times by accident
To me, this sounds like an issue that will only come up during debugging. If that is the case, I would simply do the following:
void InitFoo()
{
#ifndef NDEBUG
static bool onlyCalledOnce = TRUE;
assert(onlyCalledOnce);
onlyCalledOnce = FALSE;
#endif
...
}
The purpose of this particular wart is easily discerned just by looking at it, and it will cause a nice, big, flashy assertion failure if a programmer ever makes the mistake of calling InitFoo more than once. It will also completely dissapear in production code. (when NDEBUG is defined).
edit: A quick note on motivation:
Calling an init function more than once is probably a big error. If the end user of this function has mistakenly called it twice, quietly ignoring that mistake is probably not the way to go. If you do not go the assert() route, I would recommend at least dumping a message out to stdout or stderr.
That is exactly how I'd do it. You could use some function pointer shuffling if you want an alternative:
static void InitFoo_impl()
{
// Do stuff.
// Next time InitFoo is called, call abort() instead.
InitFoo = &abort;
}
void (*InitFoo)() = &InitFoo_impl;
Do you also need it to be multi-thread safe? Look into the Singleton pattern with double-check locking (which is surprising easy to get wrong).
If you don't want a whole class for this, another simple way is:
In a .cpp (don't declare InitBlah in the .h)
// don't call this -- called by blahInited initialization
static bool InitBlah()
{
// init stuff here
return true;
}
bool blahInited = InitBlah();
No one can call it outside of this .cpp, and it gets called. Sure, someone could call it in this .cpp -- depends on how much you care that it's impossible vs. inconvenient and documented.
If you care about order or doing it at a specific time, then Singleton is probably for you.
I do exactly that all the time with situations that need that one-time-only-but-not-worth-making-a-whole-class-for. Of course, it assumes you don't worry about thread-related issues. I usually prefix the variable name with "s_" to make it clear that it's a static variable.
Hmmm... if you don't object to using Boost, then have a look at boost::call_once:
namespace { boost::once_flag foo_init_flag = BOOST_ONCE_INIT; }
void InitFoo() {
// do stuff here
}
void FooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
void AnotherFooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
Not that I am very excited about it, but this is just another way: function object.
#import <iostream>
class CallOnce {
private:
bool called;
public:
CallOnce() {
called = false;
}
void operator()(void) {
if (called) {
std::cout << "too many times, pal" <<std::endl;
return;
}
std::cout << "I was called!" << std::endl;
called = true;
}
};
int main(void) {
CallOnce call;
call();
call();
}