All My Brain Where stuff from my brain lands

May 12, 2009

Extending std::exception

Filed under: Programming — Tags: , , , — Dennis @ 4:06 pm

So you’re writing some C++ code, feeling all object oriented and all, and you decide you’d like an application specific exception whenever one of your methods has an issue. You’d like to have error messages that the exception can print up if thrown and you think to yourself, “hey, I’ll just extend std::exception, add the error string, and be on my way.”

Problem: So here is the puzzle. What is wrong with this code:

#include 
#include 
using namespace std;
class my_error : public exception {
  private:
   string m_err;
  public:
    my_error ( const string &err) : m_err(err) {}
    const char* what() { return m_err.c_str(); }
};

Think about it for a bit before scrolling down more. Take a look at the header definition for exception.

Ok, ready to move on? Did you find the problem?

Answer:

The standard exception does not declare it’s copy constructor virtual.

 exception& operator= (const exception&) throw();

This is in part because in order to provide exception safe c++, the exception class can’t throw exceptions itself. This is the same reason using strings member variables is discouraged for exceptions. Their constructors can also throw exceptions. Anyway, the result is that if client code catches std::exception, copies the exception, and prints it, m_str hasn’t been copied and you get garbage or errors. Not what was expected was it.

Solution

This whole problem was loaded just slightly. There is already a standard exception that can take a string message as an argument.

#include 
class my_exc : public runtime_error {
 public:
  my_exc ( const string &err ) : runtime_error (err ) {}
  // there, you can add more methods here.
  // remember, you can't add data members any more here
  // than you can add them to exception derived classes though.
};

Get it? Got it? Good.

February 4, 2009

fx2lib documentation and source download

Filed under: Programming — Tags: , , , , , — Dennis @ 2:26 pm

I’ve uploaded documentation and a source download for fx2lib. Here is the copy of the Sourceforge announcement.

The fx2lib sources are stable enough to build complete firmware implementations for the cypress fx/fx2 variants of the 8051 chipset.
The current release includes library functions for:

  • delay functions
  • endpoint functions
  • register definitions
  • type definitions
  • macros for common tasks
  • GPIF functions
  • i2c functions
  • serial IO
  • USB jump tables
  • vendor commands and setup data.

Library documentation is located at: http://fx2lib.sourceforge.net/docs/

Sources can be downloaded from the project download page: https://sourceforge.net/project/showfiles.php?group_id=247216

Development on fx2lib occurs in a git repository at: http://github.com/mulicheng/fx2lib/

Check out my other posts on fx2 programming for reference. If you are interested, there is much information to discuss on the fx2lib mailing list too. Check the fx2lib home page for information on joining the list.

December 5, 2008

An Open Source Library for Writing Firmware on the Cypress FX2 with SDCC

Filed under: Hardware,Programming — Tags: , , , , , , , , , — Dennis @ 1:22 pm

After playing around with the Cypress FX2 and SDCC for the past while, I’ve developed a library of utilities that make some of the common tasks for writing firmware and performing certain functions a little easier. I’m lucky to work for a company that approves of the open source initiative and believes that it is beneficial to give back as well as receive from a wider audience of developers. That being said, I’ve created a git repository with my library:

Here is fx2lib on github: http://github.com/mulicheng/fx2lib/

You can clone it with git like this:

> git clone git://github.com/mulicheng/fx2lib.git fx2lib

Here is a short list of some of the things you can do with this library:

  1. Read/Write data on the i2c bus
  2. Handle USB and GPIF interrupts
  3. Read/Write data on to a serial console
  4. Handle the common USB vendor commands
  5. Implement your own vendor commands
  6. Program the GPIF

Hope you enjoy!

Update 12/15/08: Added project home page at Sourceforge: fx2lib home.

August 9, 2008

How much overhead does C++ bring compared to straight C?

Filed under: Programming — Tags: , , — Dennis @ 2:39 pm

The other day, I had a conversation about putting C code onto an embedded chip. I wondered if it was possible to put C++ code on there. The gist of the conversation was that the C++ libraries had a lot of overhead and the executable size would be too large for the space available on the chip. I’m not an expert on exactly how much space is available on such devices (although I plan on becoming one), but I thought I’d play around with a few things and see just what overhead a c++ program would have when compared with it’s C counterparts.

I should note that there is already comparisons of the actual language constructs of C++ vs C for embedded devices. A simple google search yielded me a few answers. I’m more interested here in library overhead. For example, how does printf compare to cout, etc. All my experiments are done on my iMac with gcc/g++.

(more…)

August 6, 2008

3 Optimizations for speeding Visual C++ compiled code.

Filed under: Programming — Tags: , , , , — Dennis @ 7:55 am

For fun, I participated in a programming contest. Instead of describing the process this time, I thought I’d include a function. Can you guess what it does? I’m changing some of the variable names so it isn’t obvious.

unsigned short result [dim][dim];
void foo(const string& info1, const string& info2, string& ret_val) {
 
 for (int x=0;x=0;--x) {
  
  use_high=x=0);
  sum += carry;
  carry = sum / 10;
  ret_val.insert( ret_val.begin(), (char)(sum % 10 + '0') );
 }
}

Anyhow, now that that fun is over, I was reading comments on a C++ forum and someone mentioned a few tips to optimizing C++ code with Visual C++. I thought I’d do a quick comparison between these and see how much of a difference it made since I was interested in program execution time and already had timing code built into my program.

  1. Release build

    I was already doing this, but I thought I’d include it for the sake of being complete.

    Debug build running time: 0.09 seconds
    Release Build running time: .02 seconds

    Obviously, this is a big one.

  2. Optimizations

    Optimizations are usually the biggest difference between release and debug builds. By default, my compiler was adding /O2 to build for maximum speed. I decided I’d enable every other optimization possible

    Release build optimizations settings

    Release build optimizations settings

    Anyway, the funny thing was, it ran faster by leaving the settings as they were. Obviously, you’ll need to test these and know what they do before simply enabling them. One thing that did seem to make a difference though, was to link against the Multi-threaded library instead of the Multi-threaded DLL. (/MT instead of /MD)

  3. Disable secure stl

    I found references to adding /D_SECURE_SCL=0 to the compiler command line. I assume if you heavily use iterators with STL, this might make more of a difference. For my little program, it didn’t seem to do much at all. I’m not completely sure it was even working. I’m assuming for now though, that it will do something, but that my program isn’t a good test case.

June 10, 2008

Timing C/C++ Code on Linux

Filed under: Programming — Tags: , , , — Dennis @ 3:37 pm

For my last post, I played around with C++ and a little programming competition. While on the topic, I decided I’d get slightly more serious and enter the next challenge.

One of the things that slightly annoyed me during the process is having to compile/run the program on Windows to enter the competion, while I’m not opposed to this, I do most of my work during the day on a Linux machine and wanted to be able to use that to develop too. For the most part, this isn’t much of an issue because the code is pretty much standard C++ and is quite cross platform compatible. I just generated a Makefile as well as the Visual Studio Project [1] and I can work on the challenge whenever I feel like devoting a little time.

Anyway, the timer code supplied is not cross platform. It only works on Windows. Since it isn’t that complicated, and I wanted to see times on both platforms, I modified the hr_time.h and hr_time.cpp to include an additional implementation for Linux.

Here are the details:

Linux Time Structures

In <sys/time.h>, you get a few functions and structures that make high resolution timing easy. The gettimeofday function returns the seconds and microseconds since the Epoch. The function operates on the timeval structure:

#include 
// snip...
timeval t;
gettimeofday(&t,NULL); // ignoring the 2nd parameter which is the timezone

In addition to being able to query the time, there are also functions for adding, subtracting, and comparing times. For this purpose, the timesub function works perfectly. You need two values (already queried with gettimeofday and and result timeval:

timeval start,stop,result;
// query the start/stop with gettimeofday during your program
timersub(&start,&stop,&result);

result now contains the difference between start/stop in seconds and microseconds.

For the sake of compatibility, the hr_time implementation wants a double for the time, where the fraction part is the number of microseconds. The nice thing is that timesub normalizes tv_usec to somewhere in the range [0,100000). Here is what I did to convert the result to a double:

return result.tv_sec + result.tv_usec/1000000.0; // 1000000 microseconds per second

Here are the completed code files if you’d like to download and look closer or use for yourself:
hr_time.h
hr_time.cpp

Have fun coding!

[1] Actually, I used Bakefile to generate the project files.

Older Posts »

Powered by WordPress

css.php
%d bloggers like this: