Tag Archives: programming

Uncategorized

debugging macro snippet

I wish I could say I came up with the below, and I suppose I did, but I more or less gathered two or three techniques I didn’t come up with into a few lines to code to make a macro useful for debugging. Its primary merits are readable output and extreme ease of use.

#define MY_MODULE_DEBUG_CATEGORY1  0x0001
#define MY_MODULE_DEBUG_CATEGORY2  0x0002
#define MY_MODULE_DEBUG_CATEGORY3  0x0004

#if !defined(MY_MODULE_DEBUG)
#  define MY_MODULE_DEBUG                 0x0000
#endif
#define _pp_string(x) #x
#define _pp_str(x)     _pp_string(x)

#if (__GNUC__ > 3)
#  define dbg(cat, fmt, ...)					\
   do {								\
      if (MY_MODULE_DEBUG_##cat & MY_MODULE_DEBUG)		\
      {								\
	 printf(__FILE__":"_pp_str(__LINE__)" [%s] "fmt,	\
		__func__, ##__VA_ARGS__);			\
      }								\
   } while (0)
#else
#  define dbg(cat, fmt, args...)				\
   do {								\
      if (MY_MODULE_DEBUG_ ## cat & MY_MODULE_DEBUG)		\
      {								\
	 printf(__FILE__":"_pp_str(__LINE__)" [%s] "fmt,	\
		__FUNCTION__ , ##args);				\
      }								\
   } while (0)
#endif
#if defined(_SOME_OS_)
#  define os_err(cat, errval)					\
   do {								\
      char *errstr = 0;						\
      error_string(errval, &errstr, 80, ERR_GET_ALL);		\
      if (errstr)						\
      {								\
	 dbg(cat, "OS ERROR:\n%s\n", errstr);			\
	 free(errstr);						\
      }								\
      else							\
      {								\
	 dbg(cat, "OS ERROR: %#lx - err_string() failed!\n",	\
	     errval);						\
      }								\
   } while (0)
#endif

Notice the “os_err” macro above, for use with OS-specific error string functions. This particular incantation is oriented toward a particular OS I interact with at work (names changed to protect the innocent), but the same idea would be applicable to any system, really.

Uncategorized

More functional support in C++

Sutter just announced that C++0x will have support for lambdas and closures.

It looks from the N2550 report that these things are motivated by a desire for some syntactic sugar to make using STL algorithms easier (which is understandable), but I hope this will lead to more first-class support for the functional programming paradigm. It has long had support for function objects, but it would be difficult to write predominantly functional programs in C++. I hope it just got a little bit easier.

My question(s): will these lambdas be serializable? In Lisp, there are a couple of ways you could ship around a closure. Ultimately, if you really wanted to, you could express the lambda as a regular list, transmit it, and then call “compile” on it. Since C++ doesn’t have a built-in way to write and compile code from within the language itself, it will have to be somewhat different (or maybe it’s time to start writing a functor serializer for the boost library).

I am a huge C++ aficionado, and this news excites me. A comment over on news.yc captures my sentiments pretty well:

Lambda functions and closures in C++. E-gads man! Wasn’t the language complex enough already!

I have to say: I love it. C++ has always been my favorite language that I don’t program in. It’s like kung-fu for programmers. You can attack any problem. But most times we don’t need kung-fu.

There’s nothing like “getting in the zone” with a good C++ program. It’s a thing of beauty. And if you’re doing stuff that you have to use the tool, like writing drivers, low-level stuff, doing some “break the rules” programming, it’s the best there is. I wrote a shell extender for windows many years ago in C++. I got to change the desktop and file system to work the way I wanted it to. Very neat stuff.

The sad fact is that most of the time you can make more money writing something with a much higher level language. And you can make it faster and adapt to the market faster. So C++ is a tougher language to use for startups, in my opinion (although it is still my favorite)

Can you imagine the trouble you can get into with macros, lambda functions, and unsafe pointers? How about throwing i some operator overloading? It’s like a playground for nuclear weapons.

Uncategorized

The Programming and Management Blog » Most Influential Programmers Results

The Programming and Management Blog » Most Influential Programmers Results

Nick Halstead recently took a month-long poll over at his blog recently of what people consider the most influential programmers, and below is the result:

1st – Linus Torvalds

2nd – Alan turing

3rd – Dennis Ritchie

4th – Donald Knuth

5th – Rasmus Lerdorf

6th – John Carmack

7th – Bill Gates

8th – Richard Stallman

9th – Tim Berners-Lee

10th – Bjarne Stroustrup

I can’t say I think this list makes any sense at all. Firstly, while Linus is definitely influential, I think it’s a stretch to say he’s the most influential of all time. Rasmus Lerdorf, similarly created something interesting, but among the most influential of all time? Bill Gates’ influence is due more to his technical strategy and business acumen, not his programming.

His own top ten list is here:

  1. John Carmack
  2. Linus Torvalds
  3. Tim Berners-Lee
  4. Douglas Andrew Bel
  5. Dennis Ritchie
  6. Bram Cohen
  7. asmus Lerdorf, Andi Gutmans & Zeev Suraski
  8. Jez San
  9. Bjarne Stroustrup
  10. Richard Bartle & Roy Trubshaw

He cheated with all the “&”s. Of course, mine would look much different, I think. Remember – this is for all time. The criteria must be something other than simple fame, which seems to be the impetus for the poll-driven list. It also should be something other than riches. Influence that sprang from work as a programmer is the criteria. It might should even be two lists: influence over the world in general (or over multiple industries), and influence in the programming and software industry. Perhaps, put simply, the idea is people who have significantly changed the way we think or do things.

Anyway, here is my list. It is unorderd, as I just don’t know how I could possibly rank the individuals. They are from different times which posed different problems, had influence in different ways which has meant different things in modern times. One might be able to do very lose rankings, but a 1-10 ranking I think isn’t very sensible.

  • Richard Stallman
  • Guy Steele
  • Tim Berners-Lee
  • Brendan Eich
  • Larry Wall
  • Kernigan & Ritchie – OK, I’m cheating a little here too, because you really can’t separate these two in their achievements.
  • David Wheeler
  • Dan Bricklin
  • Bram Cohen
  • Donald Becker
  • Bjarne Stroustrup
  • James Gosling

Have a look at Wikipedia to see info about more programmers.

Uncategorized

Best Programming Language Advice

The demons *must* be ice-skating by now.  There was an almost wholly on-topic thread on /.

The original article was an “Ask Slashdot” regarding programming languages. Below are some of the more informed comments (or so I thought), along with some of my thoughts. My apologies for not having links. I started this post using a firefox blogging plugin, and I somehow didn’t get the links included.

Don’t waste time learning a lot of computer languages. Pick one or two, learn them well, learn their standard libraries, write programs in them, and read/maintain other people’s code.

This sounds reasonable to me, but I think there are some important caveats here. I think I’d pick more than one or two languages to be in your toolbox. My preference is to be proficient in languages that fall across the following categories: statically-typed languages, dynamically-typed languages, scripting languages, functional languages, procedural languages, and object-oriented languages. Of course, there could be plenty of overlap in exactly which languages you choose. For example, my language of choice whenever practical is the C++ programming language (not “C/C++”!). C++ is a multi-paradigm language; it obviously supports procedural and object-oriented programming, but it also provides support (to varying degrees) for functional programming and generic programming (via templates and — if you can hold your nose — the preprocessor). Of course, the realities of my education required that I also be proficient in Java and C.

That takes care of the statically-typed languages. I think dynamic languages (not necessarily including their standard libraries, if there is one) are easier to learn, so why limit yourself to one? If you know C, being able to create something useful in PHP is simply a matter of learning a little Apache HTTPD administration and being handy with the PHP API. I chose to learn a little Python because it’s very useful, but also because it has some neat features and is really hot right now (which means it is gaining traction among developers and people who create tools for it, which in turn make it that much easier to use). Python has really become one of the necessary packages for a reasonably complete OS install these days. If you’ll be doing a bunch of web applications, it may be worth your while to learn Ruby; if not, then Python will be a better general-purpose dynamic language, I think. Python is very practical. There are lots of other dynamic languages out there; among the more popular are Ruby, OCaml, Lisp (and it’s dialects, like Scheme and Elisp), but don’t think it’s necessarily worth your time to be proficient in a bunch of them. Pick one or two that meet your needs.

That leaves scripting languages. The two that have been most useful to me over a number of years, and not by a close margin, are the bourne shell and sed. Of course, that gives me away as a *nix geek. I don’t have anything against Windows; I just don’t do most of my development there (and I don’t think scripting tools are as ubiquitous). I think there are very few things you could do in some other scripting language that you couldn’t do comparably using ksh99 and sed.

Update: after re-reading this, I decided to add a blurb about Perl to hopefully stem the tide of emails and comments complaining that I didn’t mention it. Fine. Perl can do everything the Bourne shell and sed can combined, plus a whole, whole lot more. It’s a true statement. Perl has incredible utility, and it’s (somewhat) portable between *nix and Windows. I just haven’t had a lot of use for it because ksh99 (or bash, as is more common) and sed take less time to learn and are sufficient to meet my needs.

So here’s the point – after the realities of my education, professional environment, and personal preferences are all accounted for, the list of languages I’m reasonably proficient in (or at least comfortable with):

  • C
  • C++
  • Java
  • C#
  • Bourne shell
  • sed
  • Python
  • PHP
  • Common Lisp
  • Scheme

This, obviously, is more than one or two. I suppose an important thing to remember is that several of these for forced on me by circumstance, and several of them were simply inevitable (seriously…what programmers out there with more than a year or two of experience, including school, can’t write a little bit of C?), and the rest were personal choice.

Spend most of your time focusing on concepts that generalize to all programming.

And

Knowing about design patterns is useful in any language. The intricacies of C++ template programming are not. If I say “That’s a singleton”, people will know what I’m talking about whether the code is written in Ruby, C++, Java, or Cobol.

This is certainly good advice. I think design patters can be a double-edged sword; they provide a neat little box to think in, but they can also convey the useful experiences and proven idioms of legions of programmers. It’s also simply smart to be able to take what you know and apply it in a broad domain spectrum.

However, I think it’s very, very important to be really proficient in at least one language. Don’t let yourself be such a generalist that you can’t answer a few questions about at least one of your languages:

  • What are its strengths?
  • What are its weaknesses?
  • Does is support tail recursion?
  • What 5 things would you change in your favorite language?
  • If I were to create a new language that could only implement 5 features from your language, which would they be?
  • Which is the best compiler?
  • What can your language be practically used for?

Once or twice a year, spend some time learning about a language you don’t know. Try to understand how it’s different than the language you normally use, and more importantly why. Look at example code and code from open source projects and try to emulate their code with your code. For example, Ruby will let you open a file, read and process each line in a while loop, then close the file. But the “ruby way” of doing it is to pass a code block to the file’s “each_line” method. After you understand the syntax and the strengths of the new language, and the idioms used by the language, decide what you like, and what you don’t. Then figure out how you can apply the new things in the language you regularly use.

I like this very much, and I think it dovetails very nicely with my previous comments; doing a detailed compare-and-contrast between your most frequently-used language and a new one will help you answer the questions above, but it will also help you keep your toolbox stocked with the most useful tools for you.

More generally, languages should be treated just like essential tools are in any other profession (or craft, if you prefer). Mechanics have buildings filled with tools, each with their purpose. They have one pegboard or cabinet that contains a small set of tools that are used very frequently and those are the kind of tools that become like extensions of the mechanics’ own limbs. That’s how programming tools should be, including languages. Go ahead and get attached to one. It gives you a little personality, but don’t sell yourself short by thinking of languages as anything other than tools.

Uncategorized

Ok, I get it (or: Gtk+ is better than I thought).

In my last post, I kinda whined about the awkwardness of the Gtkmm API. At least, it seemed that way at the time. I toyed with libglade and Gtk+ for a while first and everything seemed very straightforward and easy.

Gtkmm and libglademm are different. They seemed awkward at first, but after further investigation, I like their designs much better, and the advantages presented by C++ seem obvious. One of my primary objections was that it didn’t seem that I could hook up the default signal handlers because they were made protected members of the widget classes. At the time, it seemed to me that the only way that the default signal handlers could be used at all was by deriving classes and overriding the handlers (which are virtual, by the way). I have since discovered that the default handlers are connected by default. Also, the “slotting” mechanism used for signals — whereby signal handlers can be chained together and all executed on a single event — is pretty nifty.

Speaking strictly of Gtkmm, this doesn’t seem so bad, but I was using glade to put my UI skeleton together, and I very much liked the idea of dynamically building your UI from an XML file at program startup, rather than coding all the tedium that goes along with UI development. I also prefer C++ to C whenever possible (actually, I prefer C++ to any other language whenever remotely appropriate), which is how I got here in the first place. Anyway, glade-2 — in my opinion — isn’t very good at dealing with “custom widgets”, which includes widgets that are derived from and substantially the same as the stock widgets. One caveat I should include here is that I haven’t really gone through this whole process with glade-3 yet. Maybe it’s better. I don’t know.

Offhand, I’d say one thing that could be better in glade-2 is if, once you placed some stock widget, you could edit the classname and let glade-2 assume that the user-entered classname is the name of a class that derives from the stock widget you originally placed. Then, maybe it could support all the properties of the original widget, but actually use your derived widget at runtime when the UI is built. This would be pretty much what I want, because thus far, the only use I have for writing custom widgets is to override the default signal handlers.

Uncategorized

ksh stuff

Below is a little code I use with ksh. The wt() function can only be expected to work in an X-term. The code sequences are different for other terminal emulators.

DIRSTACK=$PWD
function dirs {
  print $DIRSTACK
}

function pushd {
  dirname=$1
  cd ${dirname:?"missing directory name."}
  DIRSTACK="$PWD $DIRSTACK"
}

function popd {
  DIRSTACK=${DIRSTACK#* }
  top=${DIRSTACK%% *}
  cd $top
}

function rfind
{
  dir=$PWD
  while [ ! -e $1 ]; do
    if [ $PWD == "/" ]; then
      command cd $dir
      return 1
    else
      command cd ..
    fi
  done

  rfdir=$PWD
  command cd $dir

  return 0
}

function wt
{
  printf "ESC]0;${@/$HOME/'~'}^G"
}

function git_dir
{
  typeset str
  rfdir=""
  rfind '.git'
  if [ $? -eq 0  ]; then
    str="\{`git branch | grep '*' | cut -d ' ' -f 2`\}"
    wt "[${rfdir}${str}]"
  else
    wt "xterm"
  fi

  echo "$str"
}

function mkprompt
{
  typeset branch

  branch=`git_dir`
  PS1="${branch}$ "
}

function cd
{
  PS1="$ "
  command cd $@
  mkprompt
}
Uncategorized

Discovering Ruby

As a software engineer who works on embedded systems and deals with things pretty close to the metal at times and primarily still works in C, I don’t get exposed to some of the new stuff that’s going on. I have to put forth extra effort to stay up to date – and even then I can’t stay on top of everything.

Given the above, it’s somewhat understandable that I’m just now discovering Ruby. I have a tendency to dismiss brand-spanking new things as vaporware, flaky, or what-have-you. I was that way about SCons when it first appeared on the scene, and I ignored it for a few years and then came back to it and liked it.

I’ve just come ’round on my cycle with Ruby. I read about it when it first appeared, but I dismissed it out of hand. After a few years (i.e., about 5 or so), I’m now re-discovering Ruby and appreciating that it fulfills more of its potential than it did before. It’s pretty neato.

Rails is another thing I’m starting to dig into. I realize I’m behind and that Rails has been out for a while and has been the hot new thing on the web for at least a year – but realize that web programming hasn’t really been my forte or one of my primary interests. I think that may be starting to change to the degree that I realize that web programming is the future, for now. Desktop applications still have a future, of course, but they won’t experience the growth, vigor, or innovation that web applications will.

Anyway, I have to get back to work. I really just wrote this so I can have a ‘ruby’ tag in my cloud.

Uncategorized

Quick and simple debug stream for C++

Ever need to set up a quick and simple debug/logging stream for your application without having to deal with large frameworks like log4cpp or *shudder* log4cxx? There’s also libcwd, which seems really neat, but also very large.

I didn’t want to use all that. I just needed a simple way to filter my output using streams without having if(…) blocks scattered all over the place. Here was my solution (I can’t remember if I came up with this on my own, or pawned it from someone else…if nothing else, I at least used the reference documentation for the boost Iostreams library). Read on to see what I did.
read more »

Uncategorized

C++ Style Redux

I just discovered the POCO library. It’s pretty neat-looking: it has a number of components that provide functionality that goes beyond the standard C++ library, such as threading support, networking, XML reading/writing, etc. The cherry on top is that not only is it similar to boost in terms of functionality, it seems smaller, more portable, and more easily targeted for embedded systems. Great, right? Read on…

However (begin rant), the style of the library really turns me off. Hugely. I haven’t even read all of the style guide (which is somewhat oppresive), but two big things I discovered right away:

  • Camel-case is used, much like in Microsoft’s MFC
  • Tab characters are used in the source code

I suppose tabs being used in the sources is pretty inconsequential for normal users of the library – although its annoying just to know that they exist.

The naming conventions though, are another animal altogether. Some of you reading this might be thinking to yourself “Holy cow! Who cares? Don’t sweat the small stuff!”. With most things, I am inclined to agree, but not on this.

Conventional style for a particular programming language is usually either defined or employed by its standards and standard libraries. This is true of Java, C, C++, C#, PHP, Scheme – you name it (there may be exceptions), and it also goes for indentation, brace placement, spacing, etc, etc, although I’m mostly concerned with naming here (everything else can be fixed by indent scripts if necessary). Take C for example. The standard C library uses almost all lowercase names, and those names tend to be brief (abbreviated if necessary), like ‘strncpy’ or ‘memset’. Structures tend to be named similarly: ‘pthread’ and ‘fileattr’, which sometimes get typedef’d to ‘pthread_t’ or ‘fileattr_t’ so that it’s clear you’re using a data structure. Most systems’ libc uses this style as do other POSIX-related libraries. Products like WindRiver’s VxWorks that deviate drastically from this convention (WindRiver in particular basically just made up their own style – to heck with convention; Microsoft was almost as bad) are an abomination to code consistency and elegance.

C++ also has its own style – the standard library (also – incorrectly – known as the stl) exhibits this. Names are typically longer than in C and multiple words are typically separated by the underscore character rather than abbreviated, although abbreviations are appropriate sometimes to keep lines from getting too long. class names are not capitalized except in the rarest circumstances. Namespaces should be used and follow the same guidelines for naming.

Why is this important to me? It’s important because you want your code to have a consistent visual style. Much of the style can be pretty arbitrary, and that’s fine. Brace placement and the width of your indent are less important to me. Even if you don’t like the way someone else chooses those elements of style, they can be changed pretty easily. Naming is not like that, and choosing non-standard (or non-conventional, if you prever) naming makes code harder to read and maintain. When I write C++ code, I want it to all look as much like the standard library as possible, with few exceptions. Then, when I want to use a library like POCO, my coding style is all blown to heck because somebody over there decided to make their own rules. Microsoft is probably the primary guilty party in this respect because of the style they chose for MFC and the ATL, as well as the Win32 API.

POCO is even internally inconsistent. On their website, they state that they have goals to:

  • Don’t reinvent wheels that have already been solved, particularly in the standard library (i.e., “thou shalt let std::string be thy string”)
  • Have consistent style.

Choosing to not reinvent implementations that work but also to ignore the conventional style (like Microsoft did) are contradictory.

Anyway, this isn’t to say that POCO shouldn’t be used. I’ll probably use it sometimes. I was just *very* annoyed by C++ code that uses the camel-case naming style.

Uncategorized

Understanding STL Containers

This article is a really great way to start understanding STL containers. It discusses the differences between a vector and a deque (a double-ended queue) (you’ll often see C++ rookies as “what’s the difference between vector and queue” or something like that, and the answer is usually “if you have to ask, just use vector”. That is an insufficient answer for a lot of people, and this article addresses it nicely).

The long and short of it is that a vector represents a sequence of elements that are accessed in “random” fashion; not meaning that you access the elements randomly, but merely that you need to be able to access an element at any position in the list. This type of usage lends itself to a different storage structure and allocation strategy than does a queue, which is a sequence from which only the ends are accessed.

A good read.