A brief analysis of C Run-time library in Visual C + +

Source: Internet
Author: User

Turn from: http://www.bccn.net/Article/kfyy/vc/jszl/200608/4278.html


1. Introduction

The Run-time library is the library file that the program needs at run time, usually in the form of Lib or DLL. C Run-time Library was born in the 1970s, the program world is still very simple, applications are single-threaded, multitasking or multithreaded mechanism in this time is also a new concept. So the C Run-time Library of this period is single-threaded.

With the development of multithreading technology in the operating system, the initial C Run-time library can not meet the requirements of the program, and there are serious problems. The C Run-time Library uses multiple global variables (such as errno) and static variables, which may cause conflicts in multithreaded programs. Suppose that all two threads set errno at the same time, and the result is that the errno will overwrite the previous one, and the user will not get the correct error message.

As a result, Visual C + + provides two versions of the C Run-time library. One version for single-threaded application calls and another version for multi-threaded applications. There are two significant differences between multithreaded run-time libraries and single-threaded Run-time libraries:

(1) A global variable similar to errno, with each thread setting one individually;

This allows the correct error message to be obtained from each thread.

(2) The data structure in the Multithread library is protected by the synchronization mechanism.

This avoids conflicts at the time of the visit.

The multithreaded Run-time libraries provided by Visual C + + are divided into static and dynamic-link libraries, and each class of run-time libraries can be subdivided into both the debug and Release editions, so Visual C + + provides 6 run-time libraries. As shown in the following table:

C Run-time Library Library files
Single thread (static link) LIBC.lib
Debug single thread (static link) LIBCD.lib
multithread (static link) LIBCMT.lib
Debug multithread (static link) LIBCMTD.lib
multithread (dynamic Link) Msvert.lib
Debug multithread (dynamic Link) Msvertd.lib

The function of 2.C Run-time Library

In addition to providing us with the necessary library function calls (such as memcpy, printf, malloc, etc.), the C Run-time Library provides another of the most important features for adding a startup function to an application.

The main function of the C Run-time Library startup function is to initialize the program, to assign the initial value to the global variable, and to load the entry function of the user program.

The entry point for a console program that does not take a wide character set is mainCRTStartup (void). Let's take this function as an example to analyze what kind of portal program the runtime Library has added to us. This function is defined in CRT0.C, and the following code is sorted and simplified by the author:

void mainCRTStartup (void)
{
int Mainret;
/* Obtain WIN32 FULL VERSION information * *
_osver = GetVersion ();
_winminor = (_osver >> 8) & 0x00ff;
_winmajor = _osver & 0x00ff;
_winver = (_winmajor << 8) + _winminor;
_osver = (_osver >>) & 0x00ffff;

_ioinit (); /* Initialize LOWIO * *

/* GET command line information * *
_ACMDLN = (char *) getcommandlinea ();

/* Access to environmental information * *
_aenvptr = (char *) __crtgetenvironmentstringsa ();

_SETARGV (); /* SET command line Parameters/*
_SETENVP (); /* Set Environment parameters * *

_cinit (); /* C Data initialization: Global variable initialization, right here. */

__initenv = _environ;
Mainret = Main (__ARGC, __ARGV, _environ); /* Call main function * *

Exit (Mainret);
}


From the above code, the runtime does some initialization before invoking the main or WinMain function of a user program. After initialization is complete, we then invoke the main or WinMain function we wrote. Only in this way can our C language runtime libraries and applications work properly.

In addition to CRT0.C, the C run-time library contains wcrt0.c, WINCRT0.C, and wwincrt0.c three files to provide initialization functions. WCRT0.C is a crt0.c wide character set, and Wincrt0.c contains the entry function for Windows applications, while WWINCRT0.C is the wincrt0.c wide character set version.

The Run-time Library source code for Visual C + + is not installed by default. If you want to view its source code, you need to reinstall Visual C + + and select the Install Runtime source code option when you reload.


3. The difference between the various C Run-time libraries

(1) Single-threaded threading

statically linked threading only for single-threaded applications, the target code for the C Run-time Library is eventually compiled into the application binaries. The/ML compilation option enables you to set up a single-line threading with static links for Visual C + +.

(2) statically linked multi-line threading

The target code for statically linked multi-line threading is also eventually compiled in the application binaries, but it can be used in multithreaded programs. The/MD compilation option enables you to set up a single-line threading with static links for Visual C + +.

(3) dynamically linked Run-time libraries

The Run-time Library of dynamic links saves all C library functions in a separate dynamic-link library MSVCRTxx.DLL, MSVCRTxx.DLL handles multithreaded issues. Use the/ML compilation option to set up a run-time library of Visual C + + that uses dynamic links. The

/MDd,/MLD, or/MTD options use the Debug Runtime library (the Run-time function Library of the debug version), corresponding to/MD,/ML, or/MT respectively. The debug version of the Runtime Library contains debugging information and has a number of protection mechanisms to help identify errors and enhance detection of errors, so it does not match release versions in performance.

To see a console program that does not use the C Run-time library correctly:

#include <stdio.h>
#include <afx.h>
int main ()
{
CFile file;
CString str ("I Love You");
TRY
{
File. Open ("file.dat", Cfile::modewrite | Cfile::modecreate);
}
CATCH (CFileException, E)
{
#ifdef _DEBUG
AfxDump << "File could not to be opened" << e->m_cause << "\ n";
#endif
}
End_catch

File. Write (str,str. GetLength ());
File. Close ();
}

A link error occurred while we were "rebuild all":

Nafxcwd.lib (thrdcore.obj): Error lnk2001:unresolved external symbol __endthreadex
Nafxcwd.lib (thrdcore.obj): Error lnk2001:unresolved external symbol __beginthreadex
Main.exe:fatal Error Lnk1120:2 unresolved externals
Error executing cl.exe.

The error occurs because Visual C + + defaults to using a single-threaded static link library for the console program, and the CFile class in MFC already has multiple threads hidden. All we need to do is select the Project->settings->c/c++ menu and options in Visual c++6.0, and modify the compilation options in Project Options.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.