Articles From Jeff Cogswell
Filter Results
Article / Updated 03-09-2017
Every time you start a new application, you create one or more processes. A process is simply executable code that is loaded into memory. The CPU reads and executes the instructions to perform the tasks you ask the application to do. When the CPU loads your application into memory, it assigns each process the application creates a Process IDentifier (PID), which is pronounced pid (think of lid with a p instead of an l). The PID is simply a number associated with the process for easy identification. In most cases, you debug an application by running it in the IDE in debug mode. However, there are some situations where you must debug the application in a different way — by attaching to its process. Attaching to the process means telling the CPU to send the instructions in the executable code to a debugger before they're executed by the CPU. In other words, you place the debugger between the executable code and the CPU. Here are some of the most common reasons for performing this task: The executable code is behaving differently in the debugger than it does when executed as a regular application. Instead of working with a debug version, you want to debug the release version. It's important to see the disassembled code as it loads in memory. You don't actually have source code to load into the debugger and execute. There are many other reasons to attach to a running process, but these are the most common reasons. Of course, before you can attach to the process, you need to know the PID. Determining the PID depends on the platform you're using. Here are some common approaches: Windows: Look at the Processes tab of the Windows Task Manager Mac OS X: Use the PS utility in the Terminal window or the Activity Monitor Linux: Use the PS utility in the Terminal window Once you have a PID, you can use it to attach to the process in Code::Blocks. The following steps get you started. Open your copy of Code::Blocks using a technique appropriate for your operating system. You see the Code::Blocks IDE open with the Start Here tab opened. Choose Debug→Attach to Process The Input Text dialog box appears. Type the PID in the PID to Attach To field and then click OK. You see the Debugger tab of the Logs and Others window appear. This tab contains information about the current process. You can type commands in the Command field to perform debugging tasks. At this point, you can type commands in the Command field to perform debugging tasks. The most common commands are: Break: Stops application execution so you can examine the application state. Step: Steps one source line (which may be several assembly lines). Continue: Restarts application execution. Go: Continues application execution to a specific point in the code. Detach: Detaches a previously attached PID so that you can safely shut the debugger down. Help: Displays additional command information.
View ArticleStep by Step / Updated 06-27-2016
Most of the Boost library works just fine by adding headers to your application code. However, a few components, such as RegEx, require a library. Before you can use a library, you must build it. After you build the library, you must add it to your application. There are two techniques for adding the required headers and libraries to an application. The first technique is to add it to the compiler settings. The second technique is to add the settings to a specific project. You use the first technique when you work with Boost for a large number of projects and require access to all libraries. The second technique is best when you use Boost only for specific projects and require access only to specific libraries. The following steps show you how to perform the project-specific setup for any library, not just the RegEx library:
View Step by StepStep by Step / Updated 06-27-2016
The static library starts with a standard C file. To make this library work well with templates, you need to delete the C file, add a C++ file, and add a header file. The following steps describe how to perform this process:
View Step by StepStep by Step / Updated 06-27-2016
Creating a library project in C++ is only a little different than creating a console application. The following steps describe how to create a library project:
View Step by StepArticle / Updated 03-26-2016
Remembering a bunch of C++ syntax can make you "loopy." The following samples show the syntax of some of the more easily forgotten C++ situations: a for loop, a while loop, and a switch statement; a class and the code for a member function; a base class and a derived class; a function, function pointer type, and pointer to the function; and a class template and then a class based on the template. Here’s a for loop: int i; for (i=0; i<10; i++) { cout << i << endl; } Here’s a while loop that counts from 10 down to 1: int i = 10; while (i > 0) { cout << i << endl; i—; } And here’s a switch statement: switch (x) { case 1: cout << “1” << endl; case 2: cout << “2” << endl; default: cout << “Something else” << endl; } Here’s a class and the code for a member function: class MyClass { private: int x; public: void MyFunction(int y); }; void MyClass::MyFunction(int y) { x = y; } Here’s a base class and a derived class: class MyBase { private: // derived classes can // not access this int a; protected: // derived classes can // access this int b; }; class Derived : public MyBase { public: void test() { b = 10; } }; Here’s a function, a function pointer type, and a pointer to the function: int function(char x) { return (int)x; } typedef int (* funcptr)(char); funcptr MyPtr = function; And here’s a class template and then a class based on the template: template <typename T> class MyTemplate { public: T a; }; MyTemplate<int> X;
View ArticleArticle / Updated 03-26-2016
In C++, a header file holds forward declarations of identifiers. Here are some of the most common C++ header files that you’ll be using, along with their correct spellings. These aren’t by any means all of them, but they are the most common: Include if you’re going to be using the string class. Include when you want to use cout and cin. Include when you want to read or write files. Include if you want advanced manipulator usage in your streams. Include for general operations, including system(“PAUSE”).
View ArticleArticle / Updated 03-26-2016
Although many C++ programmers take measures to prevent bugs, mistakes still slip through. This list of the ten most common mistakes while writing C++ code can help both new and veteran programmers: You forgot to declare the variable. You used the wrong uppercase and lowercase letters; for example, you typed Main when you meant main. You used one equal sign (=) when you were supposed to use two (==), either in an if statement or in a for loop. You forgot #include or using namespace std;. You dropped the laptop in the swimming pool. You forgot to call new and just started using the pointer anyway. You forgot the word public: in your classes so everything turned up private. You let the dog eat the remote. You forgot to type the parentheses when calling a function that takes no parameters. You forgot a semicolon, probably at the end of a class declaration.
View ArticleArticle / Updated 03-26-2016
Many C++ newbies want to create the projects they find in books by typing in the code they come across to better see how the process works. However, sometimes just getting the project started can be a serious problem. You may find step-by-step instructions online that provide you with techniques you can use to create the projects, but often, these procedures build on what you've done before. The following steps help you get a project started that includes a header, even if you jump to this point directly without getting all the prep work done. Even though the screenshots show a Windows system, the same procedure works with both the Mac and Linux platforms. Open your copy of Code::Blocks using a technique appropriate for your operating system. You see the Code::Blocks IDE open with the Start Here tab opened. Choose File→New→Project or click Create a New Project on the Start Here page that appears when you start the application. The New from Template dialog box appears. In the New from Template dialog box, click the Console Application icon found in the Projects tab, then click Go. You may see the Welcome page of the Console Application wizard. If so, click Next to get past it. The first usable page asks which language you want to use. Highlight C++ and click Next. You see a list of project-related questions. These questions define project basics, such as the project name. Type a name for your project in the Project Title field and a location for your project in the Folder to Create Project In field. The example uses SampleProject as the project title. However, you need to give your project a name that matches the application you want to create. Notice that the wizard automatically starts creating an entry for you in the Project Filename field. It's best to simply use the default name in the Project Filename field. Click Next. You see the compiler settings. Most of the projects in this book use the default compiler settings, which means using the GNU GCC Compiler option in the Compiler drop down list box. However, if you look at the Compiler drop-down list, you see that Code::Blocks supports a number of compilers and you can add more to the list. The other settings control the creation and location of a Debug version (the version you use for finding problems in your code) and a Release version (the version that you send to a customer) of the application. Change any required compiler settings and click Finish. The wizard creates the application for you. It then displays the Code::Blocks IDE with the project loaded. However, the source code file isn't loaded yet. To load the source code file, you simply double click its entry in the Workspace hierarchy (such as main.cpp). Highlight the project entry (such as Sample Project) and choose File→New→File. The New from Template dialog box shows the kinds of files you can add to your project. Highlight one of the file types, such as C/C++ Header or C/C++ Source, and click Next. You see the appropriate wizard for the kind of file you're adding. This article assumes you're adding a header file. If you see a welcome page, simply click Next to get past it. Configure the header file as needed for your project. Type a filename in the Filename with Full Path field. Check individual build options or click All to add the header to all of the builds for this project. (All is the best selection for the book). You must provide a full path to the filename. Notice that the IDE automatically creates a Header Guard Word field entry for you — that prevents the compiler from adding the header to a project more than once. Using this default normally works just fine. Click Finish. The IDE creates the new file for you and automatically opens it for editing. You can repeat steps 10 through 12 as often as needed to create the entire project hierarchy. The process for adding a C++ source file is about the same as adding a header file. The only difference is that you don't need to add a header guard word. Each time you add a new file, the IDE will add it to the project hierarchy and automatically open the file for you.
View ArticleArticle / Updated 03-26-2016
A map provides a method for quickly working with lists of data in such a manner that you can access each element easily with a key. Using a map is convenient because you can access the items in a random order. However, every key must be unique. It’s not as if your application will fail if you assign a value to a duplicate key — the duplicate will simply overwrite the original value. Here’s an example: #include <iostream> #include <map> using namespace std; int main() { map<string, string> marriages; marriages["Tom"] = "Suzy"; marriages["Harry"] = "Harriet"; marriages["Tom"] = "Amy"; cout << marriages["Tom"] << endl; cout << marriages["Harry"] << endl; return 0; } Note that there are actually two men named Tom, but they have wives with different names. When you run this example, you don’t get the expected output: Amy Harriet The original value is lost because a map can only have one key named Tom. You can use a multimap to overcome this problem. A multimap has the same basic premise of letting you assign values based on a key, but the resulting variable can have duplicate entries. Here is an example of a multimap that addresses our issue: #include <iostream> #include <map> using namespace std; int main() { multimap<string, string> marriages; marriages.insert(pair<string, string>("Tom", "Suzy")); marriages.insert(pair<string, string>("Harry", "Harriet")); marriages.insert(pair<string, string>("Tom", "Amy")); for (multimap<string, string>::iterator Values = marriages.begin(); Values != marriages.end(); ++Values) { cout << (*Values).first << " is married to " << (*Values).second << endl; } cout << endl << "Women Married to Men Named Tom" << endl; multimap<string, string>::const_iterator Values = marriages.find("Tom"); int Number = marriages.count("Tom"); for (int i = 0; i < Number; i++) { cout << Values->second << endl; ++Values; } return 0; } In this case, you still create an object containing two string objects, the first of which is the key. An insert() function lets you add new entries to marriages. The technique is different from using a standard map, but the result is the same. Each entry consists of two string values. To display the entries, you must work with iterators. The example shows two approaches you can use. The first lists all of the entries in marriages. It begins by creating an iterator that points to the beginning of marriages using the marriages.begin() function. The loop continues while Values isn’t equal to marriages.end(). Notice the prefix notation used to update Values to the next entry in the list. It’s also important to note that Values provides a pointer to the data, so you must use either (*Values).first to access the first string in the entry or Values->first. A multimap is actually quite flexible. You can count the number of duplicate key entries using the count() function. In order to use this function, you must provide the key value you want to locate. The find() function makes it possible to create an iterator that only contains the entries for a specific key. The example shows a technique for iterating through the values that you find. The output from this example looks like this: Harry is married to Harriet Tom is married to Suzy Tom is married to Amy Women Married to Men Named Tom Suzy Amy
View ArticleArticle / Updated 03-26-2016
Static arrays are allocated on the stack, which can limit their usability. Dynamic arrays are allocated on the heap, which means they're only limited by the size of memory. Admittedly, you'll find a few other differences between dynamic and static arrays, but the bottom line here is that, although dynamic arrays require a little more work to use because you must manage the memory yourself, they also provide added flexibility in working with data. More than likely you'll want to handle complex data when making use of dynamic arrays. The example in this online article aims to please by looking at how you can use a dynamic array with a structure. Here is an example of the code you might use: #include <iostream> #include <new> using namespace std; struct Employee { string Name; int Age; }; int main() { Employee* DynArray; DynArray = new (nothrow) Employee[3]; DynArray[0].Name = "Harvey"; DynArray[0].Age = 33; DynArray[1].Name = "Sally"; DynArray[1].Age = 26; DynArray[2].Name = "Jeff"; DynArray[2].Age = 52; cout << "Displaying the Array Content" << endl; for (int i = 0; i < 3; i++) { cout << "Name: " << DynArray[i].Name << "tAge: " << DynArray[i].Age << endl; } delete[] DynArray; return 0; } In this example, the code begins by creating an Employee struct that contains the employee name and age. You could use any sort of data container desired — this one just happens to be a struct. In order to create a dynamic array, you define a pointer to the array variable. This act places the variable on the heap, rather than the stack. You then create the array, which contains three Employee entries in this case. The code fills in the data and then uses a loop to display the results on screen. Here is what you should see when you run the example. Displaying the Array Content Name: Harvey Age: 33 Name: Sally Age: 26 Name: Jeff Age: 52 Notice that you access the individual members of Employee by accessing the required array index and then using dot syntax to specify the member name. It's important to remember that the dynamic array acts like any other array in that you access an index to obtain a specific entry. It's essential to use delete[] to free the memory used by DynArray. Otherwise, your application will have a memory leak that will eventually affect system performance or at least cause it to do funny things. Because our systems are already funny acting enough, it's probably a good idea to ensure your application doesn't' contribute to the problem.
View Article