Nicolás Brailovsky


A modern blog

NEW: Anonymous objects in C++

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

There are not many cases in which you can have an anonymous *anything* in your code, yet there’s an idiom in C++ which lets you use an object with an anonymous type. Like this:

void foo()
{
   struct {
      int x;
   };
}

Why would this be useful, you may ask. That’s a valid question. This idiom can be very useful to write callbacks, like this:

struct Interface {
   void callback() = 0;
};

void bar(Interface &c);

void foo()
{
   struct : public Interface {
      /* ... */
   } x;

   bar(x);
}

I am not aware of many other uses for an anonymous type. Even more considering this idiom can now be replaced with a much cleaner lambda. But hey, it looks cool!

Fixing end of line styles between Linux and Windows with SVN

author Posted by: nico on date Dec 13th, 2011 | filed Filed under: Linux, Programming

Quite a mouthful for such an easy thing. Don’t you just hate when half the people in a project use CR/LF and the other half just LF?

Luckly this is easy to fix, assuming you are using svn. You can use something called auto-props to setup the eol style for different file types.

Set it once for the project, never worry again. Anyone knows its git counterpart?

C++: Checking if a method exists in a parent class

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

I like Google test and Google mock (C++ only) a lot. These are really great tools to ensure the quality of your code. They do have one problem however, especially when working with a legacy codebase: many times you need to change a signature for a function and your tests begin to fail. Those tests shouldn’t really fail, they shouldn’t compile at all because you’re now trying to mock a function which doesn’t exists anymore.

I worked on a patch to check if a class and its parent share the same methods, but I hit some major roadblocks which I believe cannot be saved:

  • You have no way of detecting if the parent’s method is actually virtual. It may have the same signature, yet if it isn’t virtual the mock serves no purpose
  • You have no (easy) way of detecting if the method is defined in your parent’s parent

Even though this code will never be useful, I thought I might as well post this here, just in case anyone comes up with a solution for those problems.

  1. // :!g++ foo.cpp -lgtest_main -lgmock && ./a.out
  2. #include <gtest/gtest.h>
  3. #include <gmock/gmock.h>
  4. using namespace testing;
  5.  
  6. /**
  7.  * "Real" application
  8.  */
  9. class Foo {
  10.         public:
  11.         virtual int bar(int) { return 1; }
  12.         //virtual int bar(void) { return 1; }
  13. };
  14.  
  15. class Do {
  16.         public:
  17.         int something(Foo &amp;foo){ return foo.bar(1); }
  18. };
  19.  
  20. /**
  21.  * Class used to compare method ptrs. We need to inherit from class C
  22.  * to forward the calls to the derived methods.
  23.  */
  24. template <class C, class D>
  25. class Mocks_Must_Exist_In : public C {
  26.         public:
  27.         // We don’t know in the derived class the typeof the parent class
  28.         // so we define a common name using some template magic
  29.         typedef C ParentClass;
  30.         // Actually we don’t know our own class either
  31.         typedef D Self;
  32.  
  33.         // Function ptr definitions are ugly so we might as well use
  34.         // a template to hide it under the rug
  35.         template <class F, class G>
  36.         void mock_created_for_unexisting_method(F f, G g){ f = g; }
  37. };
  38.  
  39. #define METHOD_EXISTS(Method) \
  40.         void defined_##Method() { \
  41.                 mock_created_for_unexisting_method(&amp;Self::Method, &amp;ParentClass::Method); \
  42.         } \
  43.  
  44. /**
  45.  * Checked mock, shouldn’t compile if Foo’s interface changes
  46.  */
  47. class FooMock : public Mocks_Must_Exist_In< Foo, FooMock > {
  48.         public:
  49.         MOCK_METHOD1(bar, int(int));
  50.         METHOD_EXISTS(bar);
  51. };
  52.  
  53. /**
  54.  * Unchecked mock, should compile if Foo’s interface changes
  55.  */
  56. class FooMock2 {
  57.         public:
  58.         MOCK_METHOD0(bar, int());
  59. };
  60.  
  61. TEST(FooTest, ThisShouldCompile) {
  62.         FooMock foo;
  63.         EXPECT_CALL(foo, bar(_)).WillOnce(Return(42));
  64.         EXPECT_EQ(42, Do().something(foo));
  65. }
  66.  

Vim Tip: Converting to a Beamer frame

author Posted by: nico on date Dec 1st, 2011 | filed Filed under: Vim Tips

Today we’ll learn how to convert the text under the cursor to a Beamer frame, yet it’s easy to apply the same technique for other stuff:

map xi\begin{frame}{TITLE}\end{frame}kp

Lets analyze it
* xi cut whatever is selected and enter insert mode
* \begin{frame}{TITLE}\end{frame} write the beamer frame declaration
* kp go up one line and paste what was on the buffer

You can do something like this whenever you need to map text in Vim, it’s very easy.

svn tip: branch stable version, then use externals

author Posted by: nico on date Nov 24th, 2011 | filed Filed under: Programming

Even though the title says svn, this tip is applicable probably for any version control system. Imagine the following scenario: You have project BestAppEver. BestAppEver depends on BestLibEver. Both are using svn. How do you handle this on your version control system?

One way, the wrong way, that I have seen lots of times is to just include a copy of BestLibEver inside BestAppEver, like this:

This is horrible, whenever BestLibEver is updated you need to manually update BestAppEver. Thus, we come to the second (but not quite the best) solution: svn externals. They work like this:

Again, although I said svn externals, most version control systems have their own externals version. For a detailed explanation on how externals work you should read the link above, for the moment let’s just say this is enough to setup the external:

  1. $ svn pe svn:externals .
  2. # This will open your default editor. Now write this:
  3. LibName           LibURL

Now every time you run an svn update, it will fetch the latest version of BestLibEver. We have a problem though: BestLibEver may be a project with a lot of commits, and the head revision may be very unstable. Not only it may crash (being a development version, it wouldn’t be a strange thing) but also its interfaces may be constantly changing. And we certainly don’t want to spend all day just changing our wrappers to make the project compile again.

There is a solution for this, and we don’t have to go back to the first method of just copying the trunk to our repository: we can ask the maintainer of BestLibEver to just create a branch (or a tag, for this case it’s pretty much the same) for a stable version and then use an external to that branch. Like this:

Now the team developing BestLibEver can work without complaints from their users and BestAppEver can have a stable svn, with controlled lib upgrades whenever they want.

Fixing some annoying GTK Warnings

author Posted by: nico on date Nov 22nd, 2011 | filed Filed under: Uncategorized

So, new Buguntu upgrade, new problems. The usual deal. I don’t like Unity so I installed the usual gnome desktop. Now when I start gVim I get a bunch of errors like this:

  1. (gvim:7189): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap"

OK, not errors, just warnings. I don’t like them anyway, so I did this to fix it:

  1. sudo apt-get install gtk2-engines-pixbuf

Now it works. One problem less, NaN to go… time to move back to Debian?

C++ name mangling

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

There is a topic I have referred to several times on this blog, yet in four years I still haven’t explained what it is. I plan to correct this by explaining a little bit about C++ name mangling, and although I won’t expect to write anything you couldn’t learn by reading Wikipedia, I’ll try to have a more practical approach.

Whenever you compile and link something, there is a lot of information the compiler deduces that you don’t really care about. Things like calling conventions, overloads or namespaces. Yet this information is crucial for other stages of the compiler (or linker) to work. For this reason, the compiler will create a decorated version of any object’s or function’s name.

In its most simple case, it would be something like this:

  1.  
  2. void overloaded_function(int);
  3. void overloaded_function(string);
  4.  

Which would then be translated to something like:

  1.  
  2. void fastcall_int_overloaded_function(int);
  3. void fastcall_string_overloaded_function(string);
  4.  

Of course, for more complex functions (like class methods) the mangling is much more complicated. Also, remember that’s just a mangling convention I just invented, and most likely not used by any compiler in existence.

Although for the most part we can just ignore name mangling, this has a couple of consequences of which we should be aware:

Creating a name for anonymous objects/functions

I will not explain much about this, it might be the topic of another post, but there are certain cases in which you can have a struct or a function defined inside another object anonymously. In these cases, the mangler will assign some sort of denomination for this anonymous object.

Linking with C symbols

C has no mangling. It just doesn’t need it. This has a very important consequence, whenever you use C code in C++ you need to specify that your doing so, by using an extern “C” declaration.

Debugging

gdb already takes care of this so it may be transparent to you, but if you are using a debugger not aware of how your compiler mangles names, you may end up with a lot of very difficult to understand names.

Bonus: Demangling C++ names

If you find yourself in the last case, for example when running an nm to get the names defined in a (compiled) object, you can use c++ filt. Like this:

  1.  
  2. nm foo.o | c++filt
  3.  

New Buguntu, new GUI, new problems

author Posted by: nico on date Nov 1st, 2011 | filed Filed under: Linux

I updated Ubuntu to 11.10 in one of three computers I regularely use. Lot’s of problems and very little improvements. Granted, sound now works by default (finally) but dual screen suport is still less than what I would expect from Windows 98. On top of that, the biggest change is the GUi.

WTF! My computer is not a tablet, give me back my menu. While using my phone it’s nice to have only a couple of icons to click. With two big monitors, I miss my launch bar, a propper clock, my custom applets and the applications menu… everything that makes the GUI usable.

Luckly Ubuntu provides a way to revert to the “classic” desktop, you just need to apt-get install gnome-session-fallback (WTF? I need to INSTALL it? If you plan to roll out a new experimental GUI, at least let me opt-out without downloading more stuff). Of course, since now Ubuntu comes with Gnome 3 even more fun ensues.

Did you plan to customize your toolbars? Well, good luck with that. Apparently now the applets that work for the old Gnome won’t work for Gnome 3. Yes, they implemented a new cool applet system, whatever, I just want a port of the old ones I had.

Oh, if you plan to move things around you’ll have to do some research first. See that hideous clock up there, in the top bar? How would you get it to the lower-right corner? Why, hold alt and then right click to see the move menu. Super intuitive. I wonder if they inspired themselves on ribbon.

I don’t understand the tablet-interface-ftw fad, I was happy with my console multiplexer and I want to keep it unobtrusive, as gnome 2 was. Time to switch to XFCE?

Annoying “unable to find a medium containing a live file system” in Ubuntu

author Posted by: nico on date Oct 27th, 2011 | filed Filed under: Linux

Sometimes you may get this message when installing Ubuntu. And it’s not very helpful, the install just dies.

Assuming you created the installer appropriately (usb, live cd, whatever), once you reached that message it means that the BIOS already recognized your device as bootable, loaded the bootloader and started executing it. So it’s the bootloader that can’t find the image, yet that doesn’t make sense if you think about it carefully: if the installer was properly created, that shouldn’t happen.

Well, after fighting for a while I realized that some DVD drives connected to a high speed SATA port  will give this kind of message error. From the message it’s not very clear what causes it, so you can try with one of the crazy kernel options like noapic. If that doesn’t work, you can try to change the SATA mode in the BIOS. ACHI worked for me.

http://www.makarras.org/2008/06/17/gandalf/

Passwordless ssh

author Posted by: nico on date Oct 25th, 2011 | filed Filed under: Linux

This is one of those things that are terribly easy nowadays, but since I only do it every once in a while I never remember how it’s done: setting up a passwordless ssh. I won’t write any explanation, just the command to set it up so I can keep it as reference for the next time I have to do it:

  1.  
  2. ssh-keygen -t rsa && ssh-copy-id USR@HOST
  3.  

You might also want to specify that HOST requires USR, instead of $(whoami), so you won’t have to type ssh USR@HOST next time you want a passwordless loggin. This can be done in /etc/ssh/ssh_config, like this:

  1.  
  2. Host $HOST
  3.         User $USER
  4.  

Replace as needed.