Nicolás Brailovsky


A modern blog

Makefiles

author Posted by: nico on date Aug 18th, 2011 | filed Filed under: Makefiles

For open source projects, makefiles are a must. All C++ projects need them, even though cmake is strong nowadays, and even though Java has its own version (actually, several of them, but that’s not important now) a makefile could be used.

Even if it is an ubiquitous build system, it is pretty much outdated nowadays, and although using its basic features is easy, mastering it is a complex task. Worst still, mastering makefiles means you’ll probably produce write-only-code, and as makefiles are code themselves, and must therefore be maintained, this can be a nuisance to a newcomer to your project.

There’s an upside to makefiles being code: they can be reused. Once you find a configuration that suits your development process, you don’t need to write it again. I’ll post here some of the main targets I ussually include in a common.mk. As I mentioned, it’s mostly write-only-code, yet you may find it useful:

  1. # Dependency directoy
  2. df=$(BUILD_DIR)/$(*D)/$(*F)
  3.  
  4. $(OBJECTS): $(BUILD_DIR)/%.o: %.cpp
  5.         @mkdir -p $(BUILD_DIR)/$(*D)
  6.         $(COMPILE.cpp) -MD -o $@ $<
  7.         @cp $(df).d $(df).P; \
  8.         sed -e ‘s/#.*//’ -e ‘s/^[^:]*: *//’ -e ‘s/ *\\$$//’ \
  9.                 -e ‘/^$$/ d’ -e ‘s/$$/ :/’ < $(df).d >> $(df).P; \
  10.         rm -f $(df).d
  11.  
  12. $(MAIN_OBJ): $(MAIN_SRC)
  13.         $(COMPILE.cpp) -MD -o $@ $<
  14.  
  15. # Binary name depends on BIN_DIR/BIN_NAME, so the call to create BIN can
  16. # be forwarded to BIN_DIR/BIN_NAME
  17. $(BINARY): $(BIN_DIR)/$(BINARY)
  18. $(BIN_DIR)/$(BINARY): $(OBJECTS) $(DEPS_OBJECTS) $(MAIN_OBJ)
  19.         @mkdir -p $(BIN_DIR)
  20.         @# Workaround for a linker bug: if the libs are not
  21.         @# at the end it won‘t link (something to do with how the linker
  22.         @# lists the dependencies… too long for a comment, rtfm
  23.         g++ $(CXXFLAGS) $^ -o $(BIN_DIR)/$@ $(LDFLAGS)
  24.         @#$(LINK.cpp) $^ -o $@
  25.  
  26. -include $(DEPENDS)

How is this used? Well, don’t even try to understand the dependency autogeneration, it’ll make your head explode.

  1. $(OBJECTS): $(BUILD_DIR)/%.o: %.cpp

This defines a rule for building .o objects; a variable named OBJECTS should be present when including this file.

  1. $(MAIN_OBJ): $(MAIN_SRC)

A special rule is defined for a main object (actually this is needed to compile the tests, which we’ll do next time, since you may have a different main function).

  1. $(BINARY): $(BIN_DIR)/$(BINARY)
  2. $(BIN_DIR)/$(BINARY): $(OBJECTS) $(DEPS_OBJECTS) $(MAIN_OBJ)

And finally, a rule for to create the real binary. Next time I’ll add some cool features for TDD to this makefile.

Living on a null object

author Posted by: nico on date Aug 16th, 2011 | filed Filed under: C++

Check this out:

  1. struct S {
  2.    int f(){ return 42; }
  3. };
  4.  
  5. int main() {
  6.    S *x = (S*) NULL;
  7.    return x->f();
  8. }

What does this do? Does it compile? Does it crash? I’ll give you a second.

Ready? It does compile, OK
But it doesn’t crash.
Why, you may ask
Think about it, you must.

The compiler will mangle S::f and translate this into something like:

  1. struct S {};
  2.  
  3. int mangled_S_f(struct S *this){
  4.    return 42;
  5. }
  6.  
  7. int main() {
  8.    S *x = (S*) NULL;
  9.    mangled_S_f(x);
  10. }

Now, in this new “translated” code, what do you think? Will it crash? It won’t, since no one is going to dereference “this”. Crazy, huh? This crazy idiom also allows even crazier things, like C++ objects committing sepuku

Vacations are over

author Posted by: nico on date Aug 15th, 2011 | filed Filed under: Funny, Meta-post, Programming

Long time without updates. I guess I needed vacations from the blog. It was not the first time and it probably won’t be the last one I take, but I’m back now with another truckload of C++ ramblings and misc stuff. Like this one:

Funny queries: What Google thinks of me

author Posted by: nico on date Jul 12th, 2011 | filed Filed under: Meta-post

It’s been a long time since I used the metapost category. I’ve been taking a look at the queries received by Google for which this blogs shows up. Some of them are quite peculiar, some of them may give us an insight of what the search engine things of me. For example:

Query Impressions
grumpy old man 2,000
grumpy 400
grumpy man 400
ugly old man 250
grouchy old man 110
grumpy old 35
old grumpy man 70
grumpy gnome 12

There was a long list of variations to these phrases, but I didn’t want such a long post. Anyway, if you thought that grumpy is all Google considers me to be, brace yourself for a surprise:

Query Impressions
trained monkey 90
no life 90
funny troll
monkey using computer
tool monkey
congratulations monkey
monkey using tools

Basically, a computer using trained-troll monkey, with no life. Pretty accurate, some people may say.

Query Impressions
señal de muerte 12

Literally signal of death in Spanish. Tip: Lack of pulse.

Another common search:

hang yourself 200
how to hang yourself 90
rope to hang yourself 12

I guess those searches have a very low returning rate.

This is a query which sincerely surprised me:

Query Impressions
eliphant
eiephant
elehant
elepant
eephant
elephanth

I’ll do a public service here: it’s written ‘elephant’, buddy.

Final classes in C++

author Posted by: nico on date Jul 5th, 2011 | filed Filed under: C++
Have you ever wondered what’s the best way of having a class from which you can’t inherit, say, like Java’s final? Without any doubt, the best way is having a team capable of not doing things like inheriting from ‘class NeverEverEverInheritFromThis’. The second best way involves some magic and lots of beer:

  1. class Final {
  2.     protected:
  3.     Final() {}
  4. };
You'll need it

So, what the hell does that evil device do? Easy, it defines a protected constructor, meaning only derived classes will be able to access it (i.e. no public construction of this object). How does this stop other classes from inheriting? It doesn’t, unless we add one more keyword:

  1. class Final {
  2.     protected:
  3.     Final() {}
  4. };
  5.  
  6. class X : virtual Final {
  7. };

The virtual inheritance is meant to be used to avoid the dreaded diamond in multiple inheritance designs. It does a lot of magic with the constructors and the memory layout of the object; amongst other things, it’ll make any class which derives from X have only a single base class for Final and it’ll also make this hypothetical class call Final’s constructor without going through X first.

A complete explanation of virtual inheritance is beyond the scope of this article, but it’s enough for our Final device to know that it forces the virtual base’s constructors to be called first, thus now we can write this:

  1. class Final {
  2.     protected:
  3.     Final() {}
  4. };
  5.  
  6. class X : virtual Final {
  7. };
  8. class Y : public X {
  9. };
  10.  
  11. int main() {
  12.     X x;
  13.     Y y;
  14.     return 0;
  15. }

Try it and watch it fail!

Update 2011-07-08: Amazing how time flies. This article has been written about a year before its publishing, and, believe it or not, it’s already showing its age. What I would update on this article is the first paragraph: the best way of not having a problem with final classes is creating a design which doesn’t have artificial restrictions to the growth and extensibility of the system (i.e: don’t use final classes, they are usually a bad idea). I like that idea, I may write another article about it.

LD magic in Linux

author Posted by: nico on date Jun 28th, 2011 | filed Filed under: Linux

The linker is a magical beast which does all sort of crazy stuff with your binaries, without you even knowing it. Every Linux install has a linker living in the shadows, though seeing it in action is a rare supernatural event. There is an ancient tradition to communicate with the spirit of your linker. Not many know about this secret dark path and it’s powers to annoy even the most experienced (L)user.

You may begin your journey with the following enchanting:

  1. export LD_DEBUG=help

If everything went fine nothing will seem to happen, yet if the gods of the console have heard you, the next time you try to run any binary at all you’ll start to see the real magic. Try it, a simple “ls” will do the trick (don’t use commands which are not binaries, like echo or export, these are “hardcoded” in bash, so to speak, and won’t work since no runtime linking is necessary: they have already been linked when bash started!).

Read the help you just found. There is a lot of useful information there. Knowing the libs will give you an insight on the dependencies and the loading process of a binary. I have no idea what would be the use of knowing the files for each lib. The symbols and bindings are quite interesting, they remind me of an strace.

“all” is probably the best option to annoy a fellow programmer. Just set the env var and watch him go crazy.

Cool C++0X features X: type inference with decltype

author Posted by: nico on date Jun 10th, 2011 | filed Filed under: C++0x, Templates

After creating a wrapper object on the last entries, we were left with three syntax changes two analyze:

We already saw the first, and we’ll be talking about the other two this time. This was the original wrapper function which led us here:

  1.  
  2. template <class… Args>
  3. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  4.         std::cout << __PRETTY_FUNCTION__ << "\n";
  5.         return do_something(a…);
  6. }
  7.  

Back on topic:

decltype
This operator (yes, decltype is an operator) is a cousin of sizeof which will yield the type of an expression. Why do I say it’s a cousin of sizeof? Because it’s been in the compilers for a long time, only in disguise. This is because you can’t get the size of an expression without knowing it’s type, so even though it’s implementation has existed for a long time only now it’s available to the programmer.

One of it’s interesting features is that the expression with which you call decltype won’t be evaluated, so you can safely use a function call within a decltype, like this:

  1.  
  2. auto foo(int x) -> decltype( bar(x) ) {
  3.         return bar(x);
  4. }
  5.  

Doing this with, say, a macro, would get bar(x) evaluated twice, yet with decltype it will be evaluated only once. Any valid C++ expression can go within a decltype operator, so for example this is valid too:

  1.  
  2. template <typename A, typename B>
  3. auto multiply(A x, B y) -> decltype( x*y )
  4. {
  5.         return x*y;
  6. }
  7.  

What’s the type of A and B? What’s the type of A*B? We don’t care, the compiler will take care of that for us. Let’s look again at that example, more closely:

-> (delayed declaration) and decltype

Why bother creating a delayed type declaration at all and not just use the decltype in place of the auto? That’s because of a scope problem, see this:

  1.  
  2. // Declare a template function receiving two types as param
  3. template <typename A, typename B>
  4. // If we are declaring a multiplication operation, what’s the return type of A*B?
  5. // We can’t multiply classes, and we don’t know any instances of them
  6. auto multiply(A x, B y)
  7. // Luckily, the method signature now defined both parameters, meaning
  8. // we don’t need to expressly know the type of A*B, we just evaluate
  9. // x*y and use whatever type that yields
  10.         -> decltype( x*y )
  11. {
  12.         return x*y;
  13. }
  14.  

decltype
As you see, decltype can be a very powerful tool if the return type of a function is not known for the programmer when writing the code, but you can use it to declare any type, anywhere, if you are too lazy to type. If you, for example, are very bad at math and don’t remember that the integers group is closed for multiplication, you could write this:

  1.  
  2.         int x = 2;
  3.         int y = 3;
  4.         decltype(x*y) z = x*y;
  5.  

Yes, you can use it as VB’s dim! (kidding, just kidding, please don’t hit me). Even though this works and it’s perfectly legal, auto is a better option for this. We’ll see that on the next entry.

sshfs, quick remote mount

author Posted by: nico on date Jun 9th, 2011 | filed Filed under: Console

When all you have is ssh access to a machine you have enough to mount a remote disk to your work station. How? easy:

  1. sshfs user@host:/path/to/remote/dir /path/to/local/dir

Remember you need permission for both local and remote directories.

Cool C++0X features IX: delayed type declaration

author Posted by: nico on date Jun 7th, 2011 | filed Filed under: C++0x, Templates

In the last two entries we worked on a wrapper object which allows us to decorate a method before or after calling (hello aspects!), or at least that’s what it should do when g++ fully implements decltypes and variadic templates. Our wrapper function looks something like this (check out the previous entry for the wrapper object):

  1.  
  2. #include <iostream>
  3.  
  4. void do_something() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  5. void do_something(const char*) { std::cout << __PRETTY_FUNCTION__ << "\n"; }
  6. int do_something(int) { std::cout << __PRETTY_FUNCTION__ << "\n"; return 123; }
  7.  
  8. template <class… Args>
  9. auto wrap(Args… a) -> decltype( do_something(a…) ) {
  10.         std::cout << __PRETTY_FUNCTION__ << "\n";
  11.         return do_something(a…);
  12. }
  13.  
  14. int main() {
  15.         wrap();
  16.         wrap("nice");
  17.         int x = wrap(42);
  18.         std::cout << x << "\n";
  19.         return 0;
  20. }
  21.  

After the example, we were left with three new syntax changes to analyze:

  • -> (delayed declaration)
  • decltype
  • auto

Let’s study the -> operator this time:

-> (delayed declaration)
This is the easiest one. When a method is declared auto (I’ve left this one for the end because auto is used for other things too) it means its return type will be defined somewhere else. Note that in this regard the final implementation differs from Stroustroup’s FAQ.

The -> operator in a method’s definition says “Here’s the return type”. I’ll paste the same simple example we had last time, the following two snippets of code are equivalent:

  1.  
  2. void foo() {
  3. }
  4.  
  1.  
  2. auto foo() -> void {
  3. }
  4.  

Vim: Ni! Ni! Ni! Ni!

author Posted by: nico on date Jun 2nd, 2011 | filed Filed under: Funny, Vim Tips

Even though I have vim a Vim fan for a long time there still is a lot of stuff which amazes me about this little editor,  and this thing I last learned about it is in the “ZOMG that’s so cool I’m about to pee my pants” category. Unfortunately, if I were to draw a Venn diagram of the people who may find it cool I’d have to intersect the group of people reading my blog (yes, very small) with the group of people who like Vim and Monty Python. So, here’s to the null group:

Type :Ni! in Vim and be amazed, it’ll reply back: Do you demand a shrubbery?

Just how cool is that?