Archive for the ‘Programming’ Category

This post will describe on how to enable static and dynamic linking on gcc (GNU Compiler Collection).

By default, a library is dynamically linked, if the -l option is used to include the library.

For example, the code below will dynamically link somelib as well as libc, libstdc++, etc.

g++ file.cpp -o a.out -l somelib

Meanwhile, if the -static specifier is used, all libraries will be linked statically.

g++ file.cpp -o a.out -l somelib -static

Mixing between linking static and dynamic libraries is also possible; and there are two ways.

  1. Specify the full name of the static lib.
    • For example:

       g++ file.cpp -o a.out libsome.a -lsomelib2

    • By this way, the library libsome.a will be linked statically along with other object files. Meanwhile, somelib2 and the standard c libraries will remain dynamic.
  2. Pass additional options on to the linker.
    • The -Wl,<options> switch is used to pass on the options to the linker.
    • For example:

       g++ file.cpp -o a.out -Wl,-Bstatic -lsome -Wl,-Bdynamic -lsomelib2

    • The command above performs the same linking as method 1, as the -Wl,-Bstatic switch sets the linker in static-linking mode, and the -Wl,-Bdynamic switch sets the linker back to dynamic-linking mode.

Linking between static and shared library is just as simple as this. Hope this tutorial might help anyone encountering this problem.

The symbol (%) is used as the modulus operator in most languages including C, Java, Python and JavaScript; but some other keywords like ‘mod’ and ‘rem’ may also be used in other languages. Basically, the meaning of a modulus operation is to take the remainder when a number is being divided by another number. For example. 7 % 5 = 2, because 7 = 5 x 1 + 2. Obviously, this operation applies only to whole numbers (integers).

Let’s try out a few examples:

  1.  97 % 6 = ___
  2.  54 % 11 = ___
  3.  7 % 8 = ___
  4.  -14 % 3 = ___
  5.  19 % -4 = ___
  6.  -20 % -6 = ___

The first three are easy.

  1.  97 % 6 = 1     ( 97 = 6 x 16 + 1 )
  2.  54 % 11 = 10     ( 54 = 11 x 4 + 10 )
  3.  7 % 8 = 7     ( 7 = 8 x 0 + 7)

The confusion arises when negative integers are involved.

By standard (ISO/IEC 14882:2003), the modulus operation must yield a remainder, r such that

where a = dividend, n = divisor, and q = quotient.

In this case, q must be the result of the division operator. Division of two integers often involves rounding, and it happens that there are two different ways to perform rounding after a division. What this means is that the result of division and consequently the result of the modulus operator is implementation-specific, i.e it may varies across different compilers and languages.

C, Java and JavaScript uses the “round towards zero” method. This method is also known as the truncate method, because it simply throws away the fraction part and take only the integer part of the number. Examples are: 5.67 => 5, -6.2 => -6.

Now lets solve example 4 – 6 above:

4.    -14 / 3 = -4.6667 => -4, then -14 = 3 x (-4) + (-2). Hence, -14 % 3 = -2.

5.    19 / -4 = -4.75 => -4, then 19 = (-4) x (-4) + (3). Hence, 19 % -4 = 3.

6.    -20 / -6 => 3.3333 => 3, then -20 = (-6) x (-3) + (-2). Hence, -20 % -6 = -2.

On the other side, Python uses the “round down” (or “round towards minus infinity”) method. Compared to the previous method, the output differs only for negative numbers. Examples are: 5.67 => 5, -6.2 => -7.

The solution for example 4 – 6 above is now different:

4.    -14 / 3 = -4.6667 => -5, then -14 = 3 x (-5) + (1). Hence, -14 % 3 = 1.

5.    19 / -4 = -4.75 => -5, then 19 = (-4) x (-5) + (-1). Hence, 19 % -4 = -1.

6.    -20 / -6 => 3.3333 => 3, then -20 = (-6) x (-3) + (-2). Hence, -20 % -6 = -2.

From the discussion, are you able to offer any other conclusions? If you look closely, you should be able to find some way to deduce the sign of the result without even evaluating the modulus operation.

Feel free to share and comment below.

The very fundamental coordinate system in Microsoft Windows OS that every PC user should know has the unit of “PIXELS”. This is known as the Device Coordinate System, or more specifically Display Device (Screen) Coordinate System. In fact, many a Windows programmer has come to know only this specific coordinate system.

The coordinate system originates from the top-left corner of the screen. The X-axis extends in the positive direction when going towards the right of the screen; while the Y-extends increases in the positive direction when going downwards the screen. The direction of the y-axis is thus flipped in the opposite direction compared to the Cartesian system that we are familiar with. A “pixel” is the smallest unit representable on the screen, and it is therefore the unit used for this coordinate system.

The number of pixels that can be displayed on the screen is also referred to as the screen’s real-estate. It also depends on the resolution settings. A larger resolution (eg: 1920 x 1080) will give you more screen real estate compared to a smaller resolution (eg: 1024 x 768). However, the graphics and fonts will appear smaller if a larger resolution is used. A Windows application can query the screen resolution using the WINAPI functions such as GetDeviceCaps(HORZRES) and GetDeviceCaps(VERTRES), which would give the width and height, in pixels, of the screen respectively.

Screen coordinate system

The diagram showing the direction of x- and y-axis in the screen coordinate system

If your application only exists on the screen, that will be all you need to know. However, if you are dealing with real world dimensions, e.g: printing, I would like to introduce to you two new coordinate systems, which are the logical and physical coordinate systems.

The physical coordinate system corresponds to real world measurement units, which are gauged by two important set of standards, i.e the Metric system and the old Imperial system. The standard metric units are like millimeters, centimeters, meters, and kilometers; while the Imperial units are inch, foot, yards, and miles. The measurement values may contain floating-point values (or decimal values), e.g: 1/2 inch, 3.65cm, 1.8 miles, etc, since we can never expect real world measurements to be consisting of round values (or integers) only. Of course, these physical units are units that can be measured using physical tools, and their applications are almost seen everywhere –  trade, design, manufacturing, construction, aerospace and all sorts of engineering.

Today, almost every of the above industries uses software. It is really important that we could represent physical dimension on screen as accurately as how we could draw it on paper. Software needs to know physical dimensions.

The logical coordinate system is introduced not without reason. Back in the days when Windows 3.0 was first released, floating-point computing power is not as abundant as in today and some computers do not even have a floating-point coprocessor. Certainly, integer operations are more preferred and that is why all WinAPI functions specify integers as parameters. This includes all drawing and GDI-related calls. In order to overcome the limitation of representing physical units in integers, the logical units have come to be introduced.

The physical length that corresponds to a logical unit depends on the mapping mode used. Each device context (or drawing surface) in windows can be set to its own mapping mode.

Mapping mode Meaning
MM_HIENGLISH Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up.
MM_HIMETRIC Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up.
MM_LOENGLISH Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up.
MM_LOMETRIC Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up.
MM_TEXT Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down. (This is the default.)
MM_TWIPS Each logical unit is mapped to one twentieth of a printer’s point (1/1440 inch, also called a twip). Positive x is to the right; positive y is up.

Now, an application can draw in physical dimensions, using the mapping mode defined by its own. The application also needs to store dimension data. It is thus necessary that the programmer recognize the coordinate system used for storing the data and maintain uniformity throughout his application in order to avoid confusion. Typically, only one set of coordinate system (physical or logical, but not device coordinates) will be used for the actual storing of data. The reason device coordinate system not being used is that the measurement is device-dependent.

With logical coordinate system, you can print out a perfect 3cm x 3cm square by setting the width and height to 300 x 300 logical units, assuming you are applying the MM_LOMETRIC mapping mode.

However, there is one caveat. Using logical coordinates will let you print out accurate dimensions on paper but on screen, it gives you proportional size but doesn’t guarantee accurate dimensions. Why would you need that after all? As long as the application display a virtual ruler containing the correct scale, you wouldn’t take a ruler to measure the dimension of an object on screen, or would you? Recall that Microsoft Word also features two sets of ruler (one vertical, one horizontal), and that would tell you the real measurements of every object on the document.

Another reasoning is that Windows knows nothing about the size of your screen. What it can do is basically assume the number of pixels that makes up a logical inch. Typical this value is set at 96, and in the unit dpi (dots per inch). Hence, if your screen has a resolution of 1280 x 800, Windows assume that your screen has a virtual size of (1280/96)” x (800/96)”  = 13.333″ x 8.333″, whereas in reality your screen might be smaller, e.g:10.25″ x 6.40″ . That’s why you couldn’t display real dimensions on screen. With printer, however, the dpi of the printer device itself is usually fixed at 600 dpi or 1200 dpi, thus Windows has no problem printing out an accurate dimensions.

Back to our topic on logical units, there is one more mapping mode worth mentioning, i.e: MM_TWIPS. Each logical unit is mapped to one twip, the equivalent of 1/20 point or 1/1440 inch.

1 pt = 1/72 inch

1 twip = 1/20 pt = 1/1440 inch

These units belongs to the units that describe font size, e.g: 12 pt . Thanks to Steve Job for taking calligraphy classes and introducing fonts in the first Macintosh computer, today we can have wonderful and attractive fonts in our computers.

Font Height Measurement

Font Height Measurement

A font has several height attributes (as shown above). Try guess which attribute would represent the font size in points. Guessing net height? Yes, you’re right. Actually, The point size corresponds to the difference between tmHeight and tmInternalLeading, i.e net height. For instance, with the MM_TWIPS mapping mode in effect, a selected 12-point font might have a tmHeight value of 295 logical units and a tmInternalLeading value of 55. The font’s net height of 240 corresponds to the point size of 12 (since 12 pt = 240 twips).

After all, why should I dig myself into all these? There are many applications that simply fail to realize the relationship between the different coordinate systems. This causes the WYSINWYG (what you see is not what you get) problem- what you see on screen, you won’t definitely get it on printer. The hardest part is probably to handle the conversion between point size and pixels or  between point size and physical units. Therefore, when you are going to implement printing in your application next time, make sure you do it perfectly.

Here is fast method to compute the inverse of the square root of a number, implemented in the famous Quake3 engine.

float InvSqrt(float x)
{
    float xhalf = 0.5f * x;
    int i = *(int*)&x;
    i = 0x5f3759df - (i >> 1);
    x = *(float*)&i;
    x = x * (1.5f - xhalf * x * x);
    return x;
}

What’s behind it? Newton-Raphson method and bitwise manipulation of floating point numbers. Here goes a little explanation.

Back then, floating-point computation was a resource-intensive operation. However, with graphics cards that peaks at the TFLOPS level, computational power has increased by orders of magnitude, and you will rarely need or find this kind of tricks nowadays.

The Fun of Programming

Posted: May 14, 2011 in Programming
Tags:

“Source code is a detailed description of how things work.”

This is a quote from a book but I’ve forgotten which book it is. It basically means that to understand a system, the software tells you more than anything other. When you read a well-written source code, you can quickly absorbs knowledge on how things are implemented. This is also what fascinates me into programming for so long as it fulfills my curiosity mind.

On the fun of programming, Brooks sums it up the best in his book The Mythical Man Month:

Why is programming fun? What delights may its practitioner expect as his reward?

First is the sheer joy of making things. As the child delights in his mud pie, so the adult enjoys building things, especially things of his own design. I think this delight must be an image of God’s delight in making things, a delight shown in the distinctiveness of each leaf and each snowflake.

Second is the pleasure of making things that are useful to other people.Deep within, we want others to use our work and to find it helpful. In this respect the programming system is not essentially different from the child’s first clay pencil holder “for Daddy’s office.”

Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts and watching them work in subtle cycles, playing out the consequences of principles built in from the beginning. The programmed computer has all the fascination of the pinball machine or the jukebox mechanism, carried to the ultimate.

Fourth is the joy of always learning, which springs from the non-repeating nature of the task. In one way or another the problem is ever new, and its solver learns something: sometimes practical, sometimes theoretical, and sometimes both.

Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures. (…) Yet the program construct, unlike the poet’s words, is real in the sense that it moves and works, producing visible outputs separately from the construct itself. It prints results, draws pictures, produces sounds, moves arms. The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be.

Programming then is fun because it gratifies creative longings built deep within us and delights sensibilities we have in common with all men.

About Programming

Posted: May 14, 2011 in Programming
Tags:

This is a comic strip from codecomics.com.

Your money or your life!

Does a programmer have a dull life? It might or might not have to be true.

One thing that can be said is that programmers are perfectionists. Software engineering is in almost everywhere. All things from the software and games in your personal computer to automated systems like the teller machine to mission-critical systems such as aircraft navigation and nuclear plant operation system involves programming. In fact, programmers must ensure that their codes are bug-free so that the smoothness of the systems concerned is not compromised. Errors cannot be afforded, and therefore programmers must keep a critical eye on their work. Without them, the world would not be a better place to stay in than it is today. Cheers for programmers!!!