Debug is usually called a Debug version. It contains debugging information without any optimization, so that programmers can Debug programs easily. Release is called a Release version. It is often optimized to optimize the code size and running speed, so that users can use it well.
The real secret of Debug and Release lies in a set of compilation options. The options for the two are listed below (of course, there are other options, such as/Fd/Fo, but the difference is not important. Usually they will not cause the Release version error and will not be discussed here)
Debug version
Parameter description
/MDd/MLd or/MTd use the Debug runtime library (the runtime function library of the Debug version)
/Od turn off the optimization Switch
/D "_ DEBUG" is equivalent to # define _ DEBUG. Enable the compile and DEBUG code switch (mainly for the assert function)
/ZI creates the Edit and continue database, so that the source code does not need to be re-compiled if the source code is modified during the debugging process.
/GZ helps capture Memory Errors
/Gm enables the minimize reconnection switch to reduce the link time
Release Version
Parameter description
/MD/ML or/MT use the runtime function library of the released version
/O1 or/O2 optimization switch to minimize or minimize the program
/D "NDEBUG" Disable the Conditional compilation and debugging code switch (that is, do not compile the assert function)
/GF combines repeated strings and puts string constants in read-only memory to prevent Modification
In fact, there is no essential limit between Debug and Release. They are just a set of compilation options, and the compiler only acts according to the predefined options. In fact, we can even modify these options to get optimized debugging versions or release versions with trace statements.
Under which circumstances will the Release version go wrong?
With the above introduction, let's compare these options one by one to see how Release errors are generated.
1. Runtime Library: Specifies the Runtime function Library to be linked, which usually only affects the performance of the program. The Runtime Library of the debug version contains debugging information and uses some protection mechanisms to help identify errors. Therefore, the performance is inferior to that of the release version. The Runtime Library provided by the compiler is usually stable and does not cause Release errors. However, the Debug Runtime Library enhances error detection, such as heap memory allocation, sometimes there may be Debug errors but Release is normal. It should be pointed out that, if the Debug is wrong, even if the Release is normal, the program must have a Bug, but it may be that a certain run of the Release version is not shown.
2. Optimization: This is the main cause of errors, because the source program is basically translated directly when optimization is disabled, and the compiler will make a series of assumptions after optimization is enabled. There are several types of errors:
1. Frame Pointer (FPO for short): All call information (return address, parameters) and automatic variables are stored in the stack during function calling. If the declaration and implementation of a function are different (parameters, return values, and call methods), an error occurs. However, in the Debug mode, stack access is implemented through the address saved by the EBP register, if no errors such as array out-of-bounds (or "not many" out-of-bounds) occur, the function can normally be executed. In the Release mode, optimization will omit the EBP stack base address pointer, in this way, accessing the stack through a global pointer will cause the program to crash if the returned address is incorrect.
The strong type feature of C ++ can check the majority of such errors, but if forced type conversion is used, it will not work. You can force the/Oy-compilation option in the Release version to disable frame pointer omitting to determine whether such errors are possible. This type of error is usually caused by an error in writing the message response function of MFC. Correct:
Afx_msg LRESULT OnMessageOwn
(WPARAM wparam, LPARAM lparam );
ON_MESSAGE macro contains forced type conversion. One of the methods to prevent this error is to redefine the ON_MESSAGE macro and add the following code to stdafx. h (after # include "afxwin. h"). An error will be reported when the function is compiled incorrectly.
# Undef ON_MESSAGE
# Define ON_MESSAGE (message, memberFxn )\
{
Message, 0, 0, 0, AfxSig_lwl ,\
(AFX_PMSG) (AFX_PMSGW)
(Static_cast <LRESULT (AFX_MSG_CALL \
CWnd: *) (WPARAM, LPARAM)> (& memberFxn)
},
2. volatile variable: volatile tells the compiler that the variable may be modified by unknown methods (such as systems, other processes and threads) outside the program ). To improve program performance, the optimizer usually places some variables in registers (similar to the register keyword), while other processes can only modify the memory where the variable is located, but the value in the register remains unchanged.
If your program is multi-threaded, or you find that the value of a variable is inconsistent with the expected value and you are sure that the setting is correct, you may encounter such a problem. This type of error is sometimes manifested as the program has the fastest optimization error and the smallest optimization is normal. Add volatile to the variables you think are suspicious.
3. Variable Optimization: The optimization program will optimize the variable based on the usage of the variable. For example, a function has an unused variable. In the Debug version, it may mask an array out of bounds. In the Release version, this variable may be optimized, in this case, the array out-of-bounds will destroy the useful data in the stack. Of course, the actual situation is much more complicated than this. The related errors include illegal access, including array out-of-bounds and pointer errors. For example:
Void fn (void)
{
Int I;
I = 1;
Int a [4];
{
Int j;
J = 1;
}
A [-1] = 1;
// Of course the error is not so obvious, for example, the subscript is a variable
A [4] = 1;
}
J has an out-of-range scope when the array is out of bounds, but its space is not reclaimed, So I and j will cover up the out-of-bounds. The Release version may be optimized because I and j are not very useful, so that the stack is damaged.
3. DEBUG and NDEBUG: When _ DEBUG is defined, the assert () function is compiled, but NDEBUG is not compiled. In addition, the compilation of the TRACE () macro is also controlled by _ DEBUG.
All these assertions are compiled only in the Debug version, but are ignored in the Release version. The only exception is VERIFY (). In fact, these macros call the assert () function, but attach some library-related debugging code. If you add any program code to these macros, instead of a Boolean expression (for example, a value assignment or a function call that can change the value of a variable), the Release version will not perform these operations, this may cause errors. It is easy for beginners to make such mistakes, and the search method is also very simple, because these macros are listed above, you only need to use the Find in Files function of VC ++ to Find the place where these macros are used in all Files of the project and then check them one by one. In addition, some experts may also add Conditional compilation such as # ifdef _ DEBUG. Pay attention to it.
By the way, it is worth mentioning that the VERIFY () macro allows you to put program code in a Boolean expression. This macro is usually used to check the return values of Windows APIs. Some people may abuse VERIFY () For this reason. In fact, this is dangerous because VERIFY () violates the idea of assertions and cannot completely separate program code from debugging code, in the end, it may cause a lot of trouble. Therefore, experts suggest using this macro as little as possible.
4./GZ option: This option will do the following:
1. initialize memory and variables. Including using 0xCC to initialize all automatic variables, 0xCD (Cleared Data) to initialize memory allocated in the heap (that is, dynamically allocated memory, such as new), 0xDD (Dead Data) fill in the released heap memory (such as delete), 0xFD (deFencde Data), and initialize the protected memory (debug adds the protected memory before and after the dynamically allocated memory to prevent cross-border access ), the words in the brackets are the notes suggested by Microsoft. The advantage of doing so is that these values are very large and cannot be used as pointers (and in 32-bit systems, pointers are rarely odd values, in some systems, odd-number pointers produce runtime errors), which are rarely used as numerical values, and these values are easy to recognize, therefore, it is helpful to find the Release version errors. Note that many people think that the compiler will use 0 to initialize the variable, which is wrong (and this is not conducive to finding errors ).
2. When a function is called through the function pointer, the matching of the function call is verified by checking the stack pointer. (Prevent original form mismatch)
3. Check the stack pointer before the function returns, and confirm that it has not been modified. (Avoid out-of-bounds access and original form mismatch. When combined with the second item, you can roughly simulate frame pointer omitting FPO.) The common/GZ option will cause errors in the Debug version and the Release version is normal, because uninitialized variables in the Release version are random, this may cause the pointer to point to a valid address and mask illegal access. In addition, options such as/Gm/GF have fewer errors, and their effects are obvious and easy to find.
How to "debug" Release programs
When debugging succeeds but the Release fails, it is obviously very frustrating and often cannot be started. If you have read the above analysis and combined the specific performance of the error, it is good to quickly find the error. However, if you cannot find it at the moment, the following provides some strategies in this case.
1. As mentioned above, Debug and Release are only the differences between a set of compilation options. In fact, there is no definition to distinguish them. We can modify the compilation option of Release to narrow down the error range. As mentioned above, you can change the Release options to the corresponding Debug options one by one, for example,/MD to/MDd,/O1 to/Od, or run time optimization to program size optimization. Note: You can change only one option at a time to see which option the error disappears, and then find the option-related error accordingly. These options can be selected directly from the list in Project \ Settings.... Do not manually modify them. Since the above analysis is quite comprehensive, this method is the most effective.
2. In the programming process, you should always pay attention to testing the Release version, so as to avoid too much code and time constraints.
3. Use the/W4 warning level in the Debug version to obtain the maximum error information from the compiler. For example, if (I = 0) will cause/W4 warning. Do not ignore these warnings. This is usually caused by bugs in your program. But sometimes/W4 will bring a lot of redundant information, such as unused function parameter warnings, and many message processing functions will ignore some parameters. We can use:
# Progma warning (disable: 4702)
// Disable
//...
# Progma warning (default: 4702)
// Re-Allow to temporarily disable a warning or use
# Progma warning (push, 3)
// Set the warning level to/W3
//...
# Progma warning (pop)
// Reset to/W4
To temporarily change the warning level. Sometimes you can only use/W4 in the code that is considered suspicious.
4. You can Debug your Release version just like Debug. In Project/Settings..., select Settings for "Win32 Release", C/C ++, General for Category, and Program Database for Debug Info. Add "/OPT: REF" at the end of the Link tag Project options (do not enter the quotation marks ). In this way, the debugger can use the debugging symbol in the pdb file.
However, during debugging, you will find it difficult to set breakpoints and to find variables ?? These are all optimized. Fortunately, the Call Stack window still works normally. Even if the frame pointer is optimized, the Stack information (especially the return address) can still be found. This is helpful for locating errors.
========================================================== ========================================
For original documents of others, refer:
Differences between DEBUG and RELEASE versions and debugging problems:
. Memory Allocation Problems
1. The variable is not initialized. The following program runs well in debug.
Thing * search (thing * something)
BOOL found;
For (int I = 0; I <whatever. GetSize (); I ++)
{
If (whatever [I]-> field = something-> field)
{/* Found it */
Found = TRUE;
Break;
}/* Found it */
}
If (found)
Return whatever [I];
Else
Return NULL;
But not in release, because in debug, found = FALSE is automatically initialized for the variable, but not in release. Initialize variables, classes, or structures as much as possible.
2. Data Overflow
For example, char buffer [10];
Int counter;
Lstrcpy (buffer, "abcdefghik ");
In the debug version, the buffer's NULL overwrites the counter's high position, but unless counter> 16 M, there is no problem. However, in the release version, counter may be placed in the register, so that NULL overwrites the space in the buffer, which may be the return address of the function, leading to access error.
3. The memory allocation methods for DEBUG and RELEASE versions are different. If you apply for 6 * sizeof (DWORD) = 24 bytes for ele in DEBUG, you are actually allocated 32 bytes (32bytes for debug ), in the release version, 24 bytes are allocated to you (8 bytes for the release version). Therefore, if you write ele [6] In the debug version, there may be no problems, in the release version, access violate exists.
II. ASSERT and VERIFY
1. ASSERT will not be compiled in the Release version.
The ASSERT macro is defined in this way.
# Ifdef _ DEBUG
# Define ASSERT (x) if (x) = 0) report_assert_failure ()
# Else
# Define ASSERT (x)
# Endif
Actually complicated, but irrelevant. If you add the Code required by the program to these statements
For example
ASSERT (pNewObj = new CMyClass );
PNewObj-> MyFunction ();
In this case, pNewObj in the Release version is not allocated to space.
Therefore, when the next statement is executed, the program reports that the program has performed illegal operations. In this case, you can use VERIFY:
# Ifdef _ DEBUG
# Define VERIFY (x) if (x) = 0) report_assert_failure ()
# Else
# Define VERIFY (x)
# Endif
In this way, the code can be executed in the release version.
III. Parameter issues:
The custom message processing function must be defined as follows:
Afx_msg LRESULT OnMyMessage (WPARAM, LPARAM );
The returned value must be HRESULT type. Otherwise, the Debug will pass, and the Release will fail.
IV. Memory Allocation
Ensure uniformity of Data creation and clearing: If a DLL provides a function that can create data, the DLL should also provide a function to destroy the data. Data creation and cleanup should be at the same level.
V. DLL disaster
People will mix different versions of DLL to create a non-consistent image called "dynamic Connection Library Hell" (DLL Hell), even Microsoft said so (http://msdn.microsoft.com/library/techart/dlldanger1.htm ).
If your program uses your own DLL, note the following:
1. You cannot mix debug and release DLL versions. Both debug and release versions are release.
The solution is to put the debug and release programs under the debug and release directories of the main program respectively.
2. Never think that static connection to the database will solve the problem, which will only make the situation worse.
Debugging in the VI. RELEASE Board:
1. Change ASSERT () to VERIFY (). Find the code defined in "# ifdef _ DEBUG". If you need the code in the RELEASE version, move it out of the definition. Find the code in TRACE (...) because the code is not compiled in RELEASE. Check whether the Code required in the RELEASE is not cheap.
2. The differences brought about by variable initialization exist in different systems or between DEBUG/RELEASE versions. Therefore, initialize the variables.
3. Is there a warning during compilation? Set the warning level to 3 or 4, and ensure that no warning appears during compilation.
VII. Change the optimization option under the "C ++/C" Project in Project Settings to Disbale (Debug ). Compiler Optimization may cause many unexpected errors, please refer to http://www.pgh.net /~ Newcomer/debug_release.htm
1. You can also debug the software of the RELEASE version. Make the following changes:
Set "category" to "General" under "Project Settings" C ++/C "and" Debug Info "to" Program Database ".
Select the "Generate Debug Info" check box under the "Link" project.
Some restrictions arising from this practice:
The value of the variable in the mfc dll cannot be obtained.
All DLL projects used by the software must be modified.
In addition:
Ms bug: a ms technical document shows that the "Maximize Speed" optimization option for DLL in VC5 is not fully supported, therefore, this will cause memory errors and cause program crashes.
2. www.sysinternals.com has a program called DebugView, which is used to capture output of OutputDebugString. After running (it is estimated that it is set to system debugger), you can view output of OutputDebugString of all programs. After that, you can run your program and view debugging information without using VC.
3. There is a static code check tool named Gimpel Lint, which is said to be easy to use. Http://www.gimpel.com is just $.
References:
1) http://www.cygnus-software.com/papers/release_debugging.html
2) http://www.pgh.net /~ Newcomer/debug_release.htm