Setting up C++ build system on Linux

I was developing some C++ stuff on my Linux virtual machine and wanted to create something that would make it easy for me to compile C++ code. So I wrote up some bash code and added it into .bashrc as a function. Here’s the code:

Add this to your .bashrc script and then you should be able to compile your C++ code by typing cpprun in the base directory.

Preventing class redefinition errors in C++

I have just started learning C++ and have been getting a lot of these errors. I finally found a solution to this after spending some time on the internet.

Say for instance you have a class called “Animal” and g++ complains that this class is being redefined. Just add the following two lines at the very top of the Animal.h file:

#ifndef ANIMAL_H
#define ANIMAL_H

and add the following at the very bottom of the file:

#endif

So, if your class is called SomeClass, then it will be SOMECLASS_H instead of ANIMAL_H. You should have these in every header file. It prevents that header file from being redefined more than once.

How to extract words from a string in C# (Split string)

This is incredibly easy in C#. First of all, you need to have a string from which you want to extract words. A word is a string separated by spaces. To do that, just say:

string s = "Welcome to my blog!";

Now, when I use the Split command, it will return an array of individual strings. So, the implementation will be:

string[] words = s.Split(" ",StringSplitOptions.RemoveEmptyEntries);

As a result, words array will contain “Welcome”, “to”, “my”, “blog!”.

Writing multi-threaded code in C#

Threading in C# is no big deal. It has the easiest implementation I’ve ever seen. First of all, you need to have a method that you want to execute on a different thread. For this instance, I’ll put method called Calculate(). Now, this method has to be a void. However, it can take any amount of parameters. So, it can be:

public void Calculate()

or

public void Calculate(int x, int y)

Now that we know what to execute, we need to create a thread with this method. This is done by:

Thread t = new Thread(Calculate());

I can now run the thread by typing:

t.Start();

See Also: How do I do threaded programming in Java?