How I may help
LinkedIn Profile Email me!
Call me using Skype client on your machine

Reload this page C Programming

This article describes the internals of how to create, debug, and execute programs in the C programming language.

webpage article Google Computers > Programming > Languages > C

"C is quirky, flawed, and an enourmous success." —Dennis Ritchie (C's co-inventor)

C questions & answers during Tech Interviews

 

Topics this page:

  • Language Spec History
  • Development Workflow
  • Executables
  • Documentation
  • .C Source Syntax Basics
  • Execution
  • C IDEs, Debugging
  • Programming Utilities
  • Instances, Header, Libraries
  • C Algorithms, C#, Coding, Identifiers, Data Structures
  • Collections
  • Resources
  • Your comments???

  •  

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page


    Newsgroup: comp.lang.c

    A website external to this site Daniweb C programmers' forum

    Set screen C Language Specification History

      Date Name Comments
      1970 "Classic C" Brian Kernighan and Dennis Ritchie at Bell Research Labs (then a part of AT&T) named the new language they were creating "C" because it was the next letter in the English alphabet to the previous programming language they were using: B. They created C for a simpler, more flexible, and machine-independent language than low-level Assembler code to create their operating systemsanother page on this site They first implemented C to create Assembler code for the PDP-7 from Digital Equipment Corporation (now a part of Hewlett Packard). They then ported their new operating system to the PDP-11 and then UNIX.
      ? GCC3 -
      1989 ANSI C 89
      Rev. 1999, Corrected in 2003 INCITS/ISO/IEC 9899 C (C9X or C99) Added designators, compound literals, variable length arrays, and complex/imaginary data types.
      1999 Microsoft Visual C++ 6, C9 -
      ? ISO/IEC 14882 C++ The final C++ Standard. See the Dinkum C++ library
      2002 / 2003 C# (pronounced "see sharp")
      webpage article ECMA-334
      &
      ISO/IEC 23270
      Submitted in 2000 by Microsoft (with HP and Intel) for work by the TG2. The Microsoft CLI work by TG3 was also ratified as ECMA-335 in 2001 for use by the Mono Project open source implementation of the .NET Framework, including a C# compiler
      The dotGNU IDE and Microsoft's .NET Visual Studio with .NET SDK libraries for running with the .NET Framework, more like Javaanother page on this site Are its GDI+ graphics for real-time apps for game development?


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Classic C Development Workflow

    1. Coding:  C programmers write source code in plain-text files (each called a module) using a stand-alone text editor which may work with/within an IDE.

        Classic C modules are saved with a file suffix of .c.
        C++ modules may be suffixed by .cc or .cpp.
        C# members are suffixed by .cs

      At the top of C source files are usually include commands to specify external header fileson this page from third-party librarieson this page commonly referenced by several C programs.

    2. Pre-Processing:  Include C headerson this page and other compiler directives (such as #define DEBUG and #if DEDBUG for conditional compilation, ASSERT) are resolved (expanded) duing the first step in compilation.

      Unlike C and C++, C# preprocessing directives are handled by the compiler rather than a separate program. C# also has a conditional attribute to control conditional compilation and #region directives to structure code in VS.NET.

    3. Compiling:  Class files are built from source files by a C compiler perhaps called from within an IDE.

      The compiler issues messages to the programmer if the source code does not meet C Language Specifications. Many programmers apply additional tools to source code.

      C/C++ compilers generate assembler code specific to a machine (Intel PC, UNIX, etc.).
      C# compilers, like Java compilers, generate IL (Intermediate Language) code that the client runtime later compiles into machine language.

    4. Assembling:  In Classic C, the Assembler joins object modules together into object .DLL files.

    5. Linking:  A Linker creates an executable (.exe) file (called a program) from providing several object files.

      With .NET, the Assembler and Linker are combined into a single utility (AL.exe) which creates assemblies.

    6. Making installer files for distributing packages.

    7. Running (Invoke/Execute) the executable on the target operating systemanother page on this site to unit test functionality and debug logic errors using profilers and other utilities.

     


    C Development workflow


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Interactions Among Parts of a C Program

      Interfaces between modules are defined in header files that describe types (functions visible to modules of a program). Such files have a ".h" file extension.
      • System-wide header files furnished by the compiler
      • private, specific to the application being built by a programmer.

      Enclosing include files between < and > brackets tells the compiler to look for them in the standard include directory.
      Enclosing include files between quotes tells the compiler to look for them in the compilation directory or another directory.

      The data type of each input and output argument passed in and out of a function is defined with a parameter list

      A function that provide a return value of type void is called a procedure.

      The body within a function can contain declarations for local variables activated when execution reaches the function body.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C Documentation


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Classic .C Source Code Basics


      // hello.c - Wilson Mar - 24Dec,2001
      // The traditional first 'C' program

      #ident "@(#) Hello World"

      #include <stdheaders.h>

      /* Assignment statements:
      */
      char *format = "%s",*hello = "Hello World...\n";

      int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
      {

        printf( format, hello );
        MessageBox( NULL, "Hello", "Hello Demo", MB_OK );
        return(0);
      }
      This describes the basic syntax and conventions of C and C++ programs, reading from the bottom of a simple non-internationalizedanother page on this site c program, listed at right:

    • main() (or WinMain for Windows programs) is a special function that is always the first function executed at program start-up. So it must be included in every C program. By convention, some programmers place this at the bottom of source code files.

      The C89 standard requires main() to return a value of type int, so "int" is not necessary in front of main().

    • Parentheses ( and ) enclose a function's parameter list defining the type and name of input and output variables.

    • The body of the module is enclosed between braces { and } after "main". Within the body, opening and closing braces enclose each code block.

    • printf is a built-in standard function defined in the header file specified by the include directive. In UNIX systems, the stdio.h file is by default in folder /usr/include/stdio.h.

      \n is a special character that C uses to mark the end of a character string. In C, character strings are internally an array data structure that ends with the "zero byte" escape characteranother page on this site

      'C' is a small language with very few intrinsic operations. All the heavy work is done by explicit library function calls.

    • Each expression ends with a semicolon.

    • char (pronounced like "car") defines the character data type another page on this site. Commas separate several definitions of the same type.

    • Anything between /* and */ are ignored by the compiler as comments to programmers.

    • Anything between // and a carriage return are ignored by the compiler.

    • #ident is a directive to the compiler pre-processor. The @ and (#) codes ...


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Running Classic C Programs

      Application programs are called stand-alone if they are invoked by someone inputting on a console command-line user interface a command such as:

      Linkers read the object files created during compilation by compiler software.

      To find the version of the gcc compiler:

        cmd gcc --version

      To find the directories searched by the compiler:

        cmd gcc -print-search-dirs

      The list of shared object libraries is defined in enviornment variable LD_LIBRARY_PATH environment variable.

      To run a program from within a debugger, invoke the debugger associated with the compiler. For example:

        cmd fasd hello.exe
      or

        cmd gdb hello.exe


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Compilers and Debuggers

      There are many software products on the market to compile C source code

      Compile Command Debugger Name of Compiler IDE
      gcc gdb GNU 'C', the non-proprietary standard on the Linux operating system. -
      DJGPP (named for DJ Delorie, its author) RHIDE
      Freeware Pacific C (from HI-TECH softwre) includes an IDE.
      bcc . Borland Turbo 'C' -
      cc . IBM AIX -
      lc . Lattice 'C' available on IBM clone P.C.s and the Amiga. --
      ? . Microsoft C++ v6.1a Visual Studio 6
      csc.exe cordbg Microsoft .NET Framework (Assembly Linker AL.exe) VS.NET (Visual Studio.NET)
      lcc cdb lcc.NET for MSIL, from Princeton
      LCC-Win32 is free from Zephyr, but copyrighted by Jacob Navia Wedit
      Pelles C for Windows is a complete development kit for Windows and Pocket PC 2002. It contains a optimizing compiler, a resource compiler, a message compiler, a make utility and install builders. Its IDE provides project management, debugger, source code editor and resource editors for dialogs, menus, string tables, accelerator tables, bitmaps, icons, cursors, animated cursors, animation videos (AVI's without sound), versions and XP manifests. --

      In the GNU compiler suite the linker is called ld. However you should not run ld directly except under very special circumstances.

      Libraries have the file extension .a


    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Classic C Compiling and Linking, with Libraries, for Debugging

      To use a DOS command-line interface to pre-process, compile, assemble, and link C source file "hello.c" into an executable file named with the same suffix ("hello.exe"):

      cmd gcc -o -g -Wall hello.c -mwindows -lm -L. -Lc:/c/include -Lc:/c/lib

      The -mwindows switch is specified to compile Windows executables instead of console applications.

      The optional -lm switch links in the lib/libm.a trig math library defined in the math.h header file. This also replaces some ANSI functions. For example, libc.a's ldexp() doesn't set errno on error, but libm.a's ldexp() does.

      The standard C static library libc.a or libc.lib is automatically linked into programs. The standard C run time windows library CRTDLL.DLL provided by windows itself does not support the latest ANSI standard.

      The -L option specifies the location of libraries such as "libx.a".

      The -Wall switch turns on warning messages for new users.

      The -g switch enables a program to run in debug mode.

      To only perform pre-processing (and not create the object file), use the -P switch instead of "-0":

      cmd gcc -P hello.c

      Object files are always created with the ".o" file suffix in Linux and ".obj" in MS-DOS.

      To stop after creating object files (and not create the exe file), us the -c switch instead of -o.

      To link several object files into one executable.

        For C programs:
          cmd gcc -o -g hello.exe mymain.o mysub1.o mysub2.o

          The -g switch enables debugging.


        For C++ programs:
          cmd al.exe -o -g hello.exe mymain.o mysub1.o mysub2.o

      To remove debugging information from an executable, use the UNIX utility:

        cmd strip --strip-all hello.exe


    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen C# .NET Compilation

      The Microsoft Visual C++ Toolkit 2003 provides the core tools for developers to compile and link C++-based of managed code applications for Windows and the .NET Common Language Runtime. It uncludes the Microsoft C/C++ Optimizing Compiler and Linker; C Runtime Library with the C++ Standard Library Microsoft .NET Framework Common Language Runtime with sample code.

      Tools for C# programming are a part of Microsoft's Visual Studio product line that include a visually oriented GUI (Graphic User Interface), which initiates compilation when the programmer presses F5 or clicks on the icon associated with compilation. The output exe is stored by default in the bin\Debug subdirectory under where the project file is located.

      After putting the .NET Framework folder in the Windows Path environment variableanother page on this site
      use the command line interface to compile source file named "xxx.cs" with the simplest command:

      cmd csc xxx.cs

        This defaults to /t:exe which specifies a console application where lines display the results of Console.WriteLine commands. Alternately, /t:winexe specifies a Windows application without a console window.

      To compile an assembly into an executable:

      cmd csc.exe /t:exe /checked /debug+ /out:xxx.exe xxx.cs

        The /checked parameter specifies checking of increment operations so that an error is issued if a data type overflow occurs.

        The /debug+ parameter specifies debugging files to be generated.

        The /out: parameter specifies the location and file name for compiler output.

      To compile a DLL (class library with a manifest) for use by another .NET assembly:

      cmd csc.exe /t:library /checked /debug+ /out:...\bin\yyy.dll xxx.cs

      If you're using the VS.NET IDE, if you add a statement such as "using System.Management" in the .cs code before right clicking on "References" and selecting and adding a spcific version of the component being referenced, this message appears:

        The type or namespace name 'Management' does not exist in the class or namespace 'System' (are you missing an assembly reference?)


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Make Files and Using Compressed Files

      A Makefile is not invoked directly.
      A makefile is consumed when nmake is run in the same folder as the makefile.

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Debugging C Programs

      For a list of commands:

      > ?

      To set a breakpoint in class file pgm's main method:

      > stop in pgm.main

      To execute until the breakpoint:

      > run

      For a listing of the source at the => position:

      [] list
      cont

      In C#, to set a breakpoint at line 100:

      cordbg CSharpProgram.exe !b CSharpProgram.cs:100
      

     

      tool The FXCop for C# programs code analysis tool checks .NET managed code assemblies for conformance to Microsoft .NET Framework Design Guidelines and custom rules created by the provided SDK.

      It uses reflection, MSIL parsing, and callgraph analysis to inspect assemblies for more than 200 defects

      The tool has both GUI and command line versions,

      ErrorBank, the .NET Error Repository crawler browses newsgroups and tries to collect only threads that have a description of an error/exception and solution to the problem discussed by developers.

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C IDEs (Integrated Development Environments)

      For those who only want a better editor than Notepad (which appends “.txt” to the end of file names):

      • TextPad is geared to C coding
      • UltraEdit
      • G
      • PFE Text editor
      • Sheets finds definitions on the fly.

      Alternative IDEs:

      To use Visual Studio to compile ANSI C programs:

      1. From File > New > Project, select "Visual C++", template "Win32 Project", and name your solution and location.
      2. At the Welcome dialog, click Next, Console application, Empty Project, Finish.
      3. View Solution Explorer (CTRL+ ALT +L). It may be hidden among tabs on the right or left edge.
      4. In Solution Explorer, right-click on your project name to select Properties .
      5. Among Configuration Properties in the Tree structure, expand "C/C++", then select Advanced.
      6. In the right side pane change the property "Compile As" from "Compile as C++ Code (/TP)" to "Compile as C Code (/TC)", then OK.
      7. In the Solution Explorer, right-click on your project name, then Add, New Item, click "C++ File (.cpp)" even though you want a "C" file.
      8. But when you type in the name of the file, provide a .c suffix before clicking the Add button.
      9. Type in c code and press Ctrl+F5 to compile and run it.
      10. If you've already created .cpp file, in Solution Explorer, right-click on a Source File name to rename the file with .c extension instead of .cpp (for C++).

      Reminder Annoyances to remember when using Visual Studio.NET:

      • VS.NET does not automatically update references to a file name when it is changed.

      • So after changing default name Form1 to frmMain, remember to also change it in source code static void Main()
      • Source for early versions of the .NET Framework referenced System.Net.dll, which is unecessary since those classes are now inside System.dll.
      • VS.NET does not delete the code it had previously auto generated when the delted item was created. So search for references to an item before deleting it.

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Utilities For C Source Code

      To use NUnit from public domain Sourceforge, in your class library project reference c:\program files\NUnit\bin\NUnitCore.dll (or wherever you have it installed) and add

       using NUnit.Framework; 
      See this article

    • CSharp-Station Csharpfriends.com

    • Decompilers reverse engineering from executables back into (difficult to read) source:
    • C class file obfuscators reduce the size of C class files while it blocks decompilers.
    • Code Formatters:
    • Code Profilers analyze code execution to provide a time-aware view of a program's execution, to easily identify sluggish function bottlenecks.
    • Test Coverage tools reveal which lines of source code were executed during tests.
    • PDF publishing


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Accessing Console

      For a minimum classic C Windows program:

      #include <windows.h>

      int WINAPI WinMain (HINSTANCE hInstance,

        HINSTANCE hPrevInstance,
        PSTR szCmdLine,
        int iCmdShow)
      {
        MessageBox (NULL, "Hello", "Hello Demo", MB_OK);
        return (0);
      }

      This "launcher" program enables "relative path" by 1) getting its own file path location, 2) chopping off its own name 3) appending the FOLDER_NAME (under it), 4) uses that for the startup directory path, then 5) appends the EXE_NAME and 6) starts the program.

      #include 
      
      #define FOLDER_NAME "MyFolder"
      #define EXE_NAME "MyProgram.exe"
      
      int WINAPI WinMain(HINSTANCE hInstance, 
      	HINSTANCE hPrevInst,
              LPSTR pCmdLine, 
      	int nCmdShow)
      {
           // Create a string array of length MAX_PATH, which is a constant with value 260 defined in the platform SDK support file windef.h
           static char aPath[MAX_PATH];
           static char aProg[MAX_PATH];
           char *pSrch; // work string.
      
           // 1)
           if (!GetModuleFileName(hInstance, aPath, sizeof(aPath)))
                return 1;
      
           // 2) locate  in string aPath the last occurrence of '\\'
           pSrch = strrchr(aPath, '\\'); 
           if (!pSrch)
                return 2; // not found.
      
           // 4) Reinitiate the path string:
           pSrch[0] = '\\';
           strcpy(pSrch + 1, FOLDER_NAME);
      
           strcpy(aProg, aPath);
      
           // 5) Concatenate:
           strcat(aProg, "\\");
           strcat(aProg, EXE_NAME);
      
           // 6) Open/Start the program in a normal window:
           ShellExecute(NULL, "open", aProg, "", aPath, SW_SHOWNORMAL);
      
           return 0;
      }


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Common Libraries

      Here are the headers and the associated library functions found in ANSI compliant compilers, defined in stdheaders.h

      Header Purpose
      assert.h Diagnostics for debugging help.
      complex.h Complex numbers definitions. See page 177.
      ctype.h Character classification (isalpha, islower, isdigit)
      errno.h Error codes set by the library functions
      fenv.h Floating point environment. Functions concerning the precision of the calculations, exception handling, and related items. See page 166.
      float.h Characteristics of floating types (float, double, long double, qfloat). See page 166.
      inttypes.h Characteristics of integer types
      iso646.h Alternative spellings for some keywords. If you prefer writing the opera-tor "&&" as "and", use this header.
      limits.h Size of integer types.
      locale.h Definitions for the formatting of currency values using local conven-tions.
      math.h Mathematical arithmetic functionsanother page on this site
      setjmp.h Non local jumps, i.e. jumps that can go past function boundaries. See page 65.
      signal.h Signal handling. See page 163.
      stdarg.h Definitions concerning functions with variable number of arguments.
      stdbool.h Boolean type and values
      stddef.h Standard definitions for the types of a pointer difference, or others.
      stdint.h Integer types
      stdio.h Standard input and output.
      stdlib.h Standard library functions.
      stddef.h This file defines macros and types that are of general use in a program. NULL, offsetof, ptrdiff_t, size_t, and several others.
      string.h String handling. Here are defined all functions that deal with the standard representation of strings as used in C. See "Traditional string representa-tion in C". parse text stringsanother page on this site
      stdarg.h Functions with variable number of arguments are described here. See page 43.
      time.h Time related functions.See page 134.
      wchar.h Extended multibyte/wide character utilities
      wctype.h Wide character classification and mapping utilities This headers and the associated library functions are found in all ANSI compliant compilers.23

      If your program invokes Windows GUI functions, these headers are also needed:

      Header Purpose
      windows.h This contains several headers (like winbase.h) concentrated in a single file.
      winsock.h Network (tcpip)
      shellapi.h Windows Shell


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C++

     


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Mo' Class Libraries



    Due to a bug in Communicator, you must hold down the shift key and then click the link to download class files.)

    C Repositories:

  • Steve Holmes in Glasgow, Scottland

    tool RapTier from Canada generates C# code to use SQL databases.


  • Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C Algorithms

      In C, the behavior of a class is determined by its functions (rather than Java methods).

      Open source DBNavigator that has a VCR-like interface for navigating data and managing records. Record navigation is provided by the First, Previous, Next, and Last buttons. Record management is provided by the Create, Delete, Update, and Cancel buttons. It contains a huge portion of what every database application needs to perform.

     

    The Deitel Family's books are wordy and expensive ($75), but colorful.

    C#, How to Program

    C# For Experienced Programmers

    JoeGrip says you can learn C# in just 5 hours with their interactive audio courses online.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Compiling with C#

      To compile and generate XML documentation within

      csc.exe /out:CSharpProgram.exe CSharpProgram.cs 
      	/doc:CSharpProgram.xml
      

      The C# compiler looks for XML wrapped comments after three slashes:

      /// <summary>
      /// Summary of program
      /// </summary>
      

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C# Coding Guidelines, Standards, and Conventions

     

      This is based on information from:

      Iridium

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Object Identifier Naming & Duration

      The identifiers used to name variables and references include attributes name, data type, size, and value.

      Reminder Identifiers must start with a letter, $ or _ (underline), but not a number.
      Reminder Uppercase and lowercase alphabetic characters are differentiated.

      The state of an object is determined by the values stored in its variables.

      An identifier's duration in memory is also called its lifetime.

      • Member Variables of a class are created (instantiated) when an instance is created by invoking a new constructor. It is subject to accessibility rules and the need for a reference to the object.

        Stored in the heap, member variables are accessible as long as the enclosing object exists They are destroyed when the object is destroyed. The space they consumed are then recovered by C's garbage collection mechanisms.

      • Automatic Variables of a method are created on entry to the method (when the method is invoked). They exist only during execution of the method, and therefore is only accessible during the execution of that method. Thus, they are also known as local variables. So, local variables have automatic duration.

        Stored in the stack, they must be explicitly initialized before being used (to avoid a compiler error). They are destroyed on exit from the method.

      The keyword this. is used to reference local variables named the same as variables defined at the class instance level. This is not valid for static methods.

      An identifier's scope defines where the identifier can be referenced within a program.

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Data Structures

     

     
    Go to Top of this page.
    Previous topic this page Next topic this page

    Set screen C Developer Resources

      Certification

      Tutorials

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen C Style Guides

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Memory Allocation and Deallocation

      Risky

        memcpy(buff1, buff2, BUFFER_SIZE);
        memset(data_ptr, '\0', sizeof(struct data));
        

      Safe (r?)

        memcpy(buff1, buff2, sizeof(buff1));
        memset(data_ptr, '\0', sizeof(data_ptr[0]));
        

      Risky

        memcpy(struct_ptr1, struct_ptr2, sizeof(struct the structure));
        

      Safe(r?)

        assert(struct_ptr1 != NULL);
        assert(struct_ptr2 != NULL);
        memcpy(struct_ptr1, struct_ptr2, sizeof(struct_ptr1[0]));
        

      Bad

        free(ptr);
        

      Good

        assert(ptr != NULL);
        free(ptr);
        ptr = NULL; // Make sure it's not used again accidently.
        delete obj_ptr;
        obj_ptr = NULL;
        

     

      -

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Pointers

     

      -

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Portions ©Copyright 1996-2014 Wilson Mar. All rights reserved. | Privacy Policy |

    Search

    Related:

  • Exception Handling
  • Enterprise Computing
  • PATH & CLASSPATH
  • Design Patterns,
  • Data Types, Strings, Escape Characters, Dates, JDBC
  • Programming Logic, Operators, Functions, Threads,
  • Applications Development
  • On the web

  • How I may help

    Send a message with your email client program


    Your rating of this page:
    Low High




    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 



      Top of Page Go to top of page

    Thank you!