1.1 Calling Library Routines

To use a library routine, simply call it in your program, just as if it is defined there. For instance, suppose you write the following program and name it SAMPLE.C:

#include <stdio.h>

void main( void )

{

printf( "Microsoft C/C++\n" );

}

The program prints Microsoft C/C++ by calling the printf routine, which is part of the run-time library. Calling a library routine normally involves two groups of files:

Header (“include”) files that contain declarations, constants, and type definitions required by library routines

Library files that contain the library routines in compiled form

Header files and library files are both included with Microsoft C/C++. Header files are used when compiling, and library files are used when linking.

You include the necessary header files in your program source code with #include directives. The description of each library routine in Part 2, “Run-Time Functions,” tells you what header file the routine requires. Since printf requires the STDIO.H header file, the SAMPLE.C program contains the following line:

#include <stdio.h>

This line causes the compiler to insert the contents of STDIO.H into the source file SAMPLE.C.

After you compile the source file, you link the resulting object (.OBJ) file with the appropriate library (.LIB) file to create an executable (.EXE) file. Your object file contains the name of every routine that your program calls, including library routines. If a routine is not defined in your program, the linker searches for its code in a library file and includes that code in the executable file.

Normally, the code for standard library routines is contained in the “default library” that you create when installing Microsoft C/C++. Since the linker automatically searches the default library, you do not need to specify that library's name when linking your program. The following command links the example program with the default library:

link sample,,,;

If you call a library routine that is not contained in the default library, you must give the linker the name of the library file that contains the routine. For instance, if your program uses a Microsoft graphics routine, you would link the program using a line that includes GRAPHICS.LIB:

link sample,,, graphics.lib;

For more information about installing libraries and linking, see Getting Started and Part 3 of Environment and Tools (both are in the Microsoft C/C++ version 7.0 documentation set) or consult the installation documentation for your compiler.