This chapter explains how you can use the lint program to check your C code for errors that may cause a compilation failure or unexpected results at runtime. In many cases, lint warns you about incorrect, error-prone, or nonstandard code that the compiler does not necessarily flag.
The lint program issues every error and warning message produced by the C compiler. It also issues warnings about potential bugs and portability problems. Many messages issued by lint can assist you in improving your program’s effectiveness, including reducing its size and required memory.
The lint program uses the same locale as the compiler and the output from lint is directed to stderr. See 4.6.3 lint Filters for more information on and examples of how to use lint to check code before you perform type-based alias-disambiguation.
The lint program operates in two modes:
Basic, which is the default
Enhanced, which includes everything done by basic lint, as well as additional, detailed analysis of code
In both basic and enhanced modes, lint compensates for separate and independent compilation in C by flagging inconsistencies in definition and use across files, including any libraries you have used. In a large project environment especially, where the same function may be used by different programmers in hundreds of separate modules of code, lint can help discover bugs that otherwise might be difficult to find. A function called with one less argument than expected, for example, looks at the stack for a value the call has never pushed, with results correct in one condition, incorrect in another, depending on whatever happens to be in memory at that stack location. By identifying dependencies like this one and dependencies on machine architecture as well, lint can improve the reliability of code run on your machine or someone else’s.
In enhanced mode, lint provides more detailed reporting than in basic mode. In basic mode, lint’s capabilities include:
Structure and flow analysis of the source program
Constant propagations and constant expression evaluations
Analysis of control flow and data flow
Analysis of data types usage
In enhanced mode, lint can detect these problems:
Unused #include directives, variables, and procedures
Memory usage after its deallocation
Unused assignments
Usage of a variable value before its initialization
Deallocation of nonallocated memory
Usage of pointers when writing in constant data segments
Nonequivalent macro redefinitions
Unreached code
Conformity of the usage of value types in unions
Implicit casts of actual arguments.
Invoke the lint program and its options from the command line. To invoke lint in the basic mode, use the following command:
% lint file1.c file2.c |
Enhanced lint is invoked with the -Nlevel or -Ncheck option. For example, you can invoke enhanced lint as follows:
% lint -Nlevel=3 file1.c file2.c |
lint examines code in two passes. In the first pass, lint checks for error conditions within C source files; in the second pass, it checks for inconsistencies across C source files. This process is invisible to the user unless lint is invoked with -c:
% lint -c file1.c file2.c |
That command directs lint to execute the first pass only and collect information relevant to the second—about inconsistencies in definition and use across file1.c and file2.c—in intermediate files named file1.ln and file2.ln:
% ls file1.c file1.ln file2.c file2.ln |
This way, the -c option to lint is analogous to the -c option to cc, which suppresses the link editing phase of compilation. Generally speaking, lint’s command-line syntax closely follows cc’s.
When the .ln files are linted:
% lint file1.ln file2.ln |
the second pass is executed. lint processes any number of .c or .ln files in their command-line order. Thus,
% lint file1.ln file2.ln file3.c |
directs lint to check file3.c for errors internal to it and all three files for consistency.
lint searches directories for included header files in the same order as cc. You can use the -I option to lint as you would the -I option to cc. See 2.14 How to Specify Include Files.
You can specify multiple options to lint on the same command line. Options can be concatenated unless one of the options takes an argument or if the option has more than one letter:
% lint -cp -Idir1 -Idir2 file1.c file2.c |
That command directs lint to:
Execute the first pass only
Perform additional portability checks
lint has many options you can use to direct lint to perform certain tasks and report on certain conditions.
The lint program is a static analyzer. It cannot evaluate the runtime consequences of the dependencies it detects. Certain programs, for instance, may contain hundreds of unreachable break statements that are of little importance, but which lint flags nevertheless. This is one example where the lint command-line options and directives—special comments embedded in the source text—come in:
You can invoke lint with the -b option to suppress all the error messages about unreachable break statements.
You can precede any unreachable statement with the comment /*NOTREACHED*/ to suppress the diagnostic for that statement.
The lint options are listed below alphabetically. Several lint options relate to suppressing lint diagnostic messages. These options are also listed in Table 4–8, following the alphabetized options, along with the specific messages they suppress. The options for invoking enhanced lint begin with -N.
lint recognizes many cc command-line options, including -A, -D, -E, -g, -H, -O, -P, -U, -Xa, -Xc, -Xs, -Xt, and -Y, although -g and -O are ignored. Unrecognized options are warned about and ignored.
Turns on verbose mode, showing each component as it is invoked.
Shows each component as it is invoked, but does not actually execute it.
Suppresses certain messages. Refer to Table 4–8.
Suppresses certain messages. Refer to Table 4–8.
Creates a .ln file with the file name specified. These .ln files are the product of lint’s first pass only. filename can be a complete path name.
Creates a .ln file consisting of information relevant to lint’s second pass for every .c file named on the command line. The second pass is not executed.
Specifies the directory dir where the lint output files (.ln files) will be placed. This option affects the -c option.
-err=warn is a macro for -errwarn=%all. See 4.3.15 -errwarn=t.
Perform additional checking as specified by l. The default is -errchk=%none. Specifying -errchk is equivalent to specifying -errchk=%all. l is a comma-separated list of checks that consists of one or more of the following. For example, -errchk=longptr64,structarg.
Table 4–1 The -errchk Flags
Value |
Meaning |
---|---|
%all |
Perform all of -errchk’s checks. |
%none |
Perform none of -errchk’s checks. This is the default. |
[no%]locfmtchk |
Check for printf-like format strings during the first pass of lint. Regardless of whether or not you use -errchk=locfmtchk, lint always checks for printf-like format strings in its second pass. |
[no%]longptr64 |
Check portability to environment for which the size of long integers and pointers is 64 bits and the size of plain integers is 32 bits. Check assignments of pointer expressions and long integer expressions to plain integers, even when explicit cast is used. |
[no%]structarg |
Check structural arguments passed by value and report the cases when formal parameter type is not known. |
[no%]parentheses |
Check the clarity of precedence within your code. Use this option to enhance the maintainability of code. If -errchk=parentheses returns a warning, consider using additional parentheses to clearly signify the precedence of operations within the code. |
[no%]signext |
Check for situations in which the normal ISO C value-preserving rules allow the extension of the sign of a signed-integral value in an expression of unsigned-integral type. This option only produces error messages when you specify -errchk=longptr64 as well. |
[no%]sizematch |
Check for the assignment of a larger integer to a smaller integer and issue a warning. These warnings are also issued for assignment between same size integers that have different signs (unsigned int gets a signed int). |
Specifies the format of lint output. f can be one of the following: macro, simple, src, or tab.
Table 4–2 The -errfmt Flags
Value |
Meaning |
---|---|
macro |
Displays the source code, the line number, and the place of the error, with macro unfolding |
simple |
Displays the line number and the place number, in brackets, of the error, for one-line (simple) diagnostic messages. Similar to the -s option, but includes error-position information |
src |
Displays the source code, the line number, and the place of the error (no macro unfolding) |
tab |
Displays in tabular format. This is the default. |
The default is -errfmt=tab. Specifying -errfmt is equivalent to specifying -errfmt=tab.
If more than one format is specified, the last format specified is used, and lint warns about the unused formats.
Enables lint to report certain messages for header files when you also specify -Ncheck. h is a comma-separated list that consists of one or more of the following: dir, no%dir, %all, %none, %user.
Table 4–3 The -errhdr Flags
Value |
Meaning |
---|---|
dir |
Report the -Ncheck messages for header files included from the directory dir |
no%dir |
Does not report the -Ncheck messages for header files included from the directory dir |
%all |
Checks all used header files |
%none |
Does not check header files. This is the default. |
%user |
Checks all used user header files, that is, all header files except those in /usr/include and its subdirectories, as well as those supplied by the compiler |
The default is -errhdr=%none. Specifying -errhdr is equivalent to specifying -errhdr=%user.
Examples:
% lint -errhdr=inc1 -errhdr=../inc2 |
checks used header files in directories inc1 and ../inc2.
% lint -errhdr=%all,no%../inc |
checks all used header files except those in the directory ../inc.
Suppresses or enables lint error messages.
t is a comma-separated list that consists of one or more of the following: tag, no%tag, %all, %none.
Table 4–4 The -erroff Flags
Value |
Meaning |
---|---|
tag |
Suppresses the message specified by this tag. You can display the tag for a message by using the -errtags=yes option. |
no%tag |
Enables the message specified by this tag |
%all |
Suppresses all messages |
%none |
Enables all messages. This is the default. |
The default is -erroff=%none. Specifying -erroff is equivalent to specifying -erroff=%all.
Examples:
% lint -erroff=%all,no%E_ENUM_NEVER_DEF,no%E_STATIC_UNUSED |
prints only the messages “enum never defined” and “static unused”, and suppresses other messages.
% lint -erroff=E_ENUM_NEVER_DEF,E_STATIC_UNUSED |
suppresses only the messages “enum never defined” and “static unused”.
Use the -errsecurity option to check your code for security loopholes.
v must be one of the following:
Table 4–5 The -errsecurity Flags
If you do not specify a setting for -errsecurity, the lint sets it to -errsecurity=%none. If you do specify -errsecurity but not an argument, the lint sets it to -errsecurity=standard.
Displays the message tag for each error message. a can be either yes or no. The default is -errtags=no. Specifying -errtags is equivalent to specifying -errtags=yes.
Works with all -errfmt options.
If the indicated warning message is issued, lint exits with a failure status. t is a comma-separated list that consists of one or more of the following: tag, no%tag, %all, %none. Order is important; for example %all,no%tag causes lint to exit with a fatal status if any warning except tag is issued. The following table list the -errwarn values:
Table 4–6 The -errwarn Flags
tag |
Cause lint to exit with a fatal status if the message specified by this tag is issued as a warning message. Has no effect if tag is not issued. |
no%tag |
Prevent lint from exiting with a fatal status if the message specified by tag is issued only as a warning message. Has no effect if tag is not issued. Use this option to revert a warning message that was previously specified by this option with tag or %all from causing lint to exit with a fatal status when issued as a warning message. |
%all |
Cause lint to exit with a fatal status if any warning messages are issued. %all can be followed by no%tag to exempt specific warning messages from this behavior. |
%none |
Prevents any warning message from causing lint to exit with a fatal status should any warning message be issued. |
The default is -errwarn=%none. If you specify -errwarn alone, it is equivalent to -errwarn=%all.
Prints the path names as supplied on the command line rather than only their base names when referring to the .c files named on the command line.
Reports about old-style function definitions or declarations.
Executes lint with options contained in the file file. Multiple options can be specified in file, one per line.
Suppresses certain messages. Refer to Table 4–8.
Searches the directory dir for included header files.
Alter the behavior of /* LINTED [message] */ directives or NOTE(LINTED(message)) annotations. Normally, lint suppresses warning messages for the code following these directives. Instead of suppressing the messages, lint prints an additional message containing the comment inside the directive or annotation.
Searches for a lint library in the directory dir when used with -l.
Accesses the lint library llib-lx.ln.
Suppresses certain messages. Refer to Table 4–8.
Specifies the memory model for the program being analyzed. Also searches for lint libraries that correspond to the selected memory model (32-bit/64-bit).
Use -m32 to verify 32-bit C programs and -m64 to verify 64-bit C programs.
The ILP32 memory model (32-bit int, long, pointer data types) is the default on all Solaris platforms and on Linux platforms that are not 64-bit enabled. The LP64 memory model (64-bit long, pointer data types) is the default on Linux platforms that are 64-bit enabled. -m64 is permitted only on platforms that are enabled for the LP64 model.
Note that in previous compiler releases, the memory model, ILP32 or LP64, was implied by the choice of the -Xarch option. Starting with the Sun Studio 12 compilers, this is no longer the case. On most platforms, just adding -m64 to the command line is sufficient for linting 64-bit programs.
See the sections following this list of lint options for more information on the predefined macros.
Checks header files for corresponding declarations; checks macros. c is a comma-separated list of checks that consists of one or more of the following: macro, extern, %all, %none, no%macro, no%extern.
Table 4–7 The -Ncheck Flags
Value |
Meaning |
---|---|
macro |
Checks for consistency of macro definitions across files |
extern |
Checks for one-to-one correspondence of declarations between source files and their associated header files (for example, for file1.c and file1.h). Ensure that there are neither extraneous nor missing extern declarations in a header file. |
%all |
Performs all of -Ncheck’s checks |
%none |
Performs none of -Ncheck’s checks. This is the default. |
no%macro |
Performs none of -Ncheck’s macro checks |
no%extern |
Performs none of -Ncheck’s extern checks |
The default is -Ncheck=%none. Specifying -Ncheck is equivalent to specifying -Ncheck=%all.
Values may be combined with a comma, for example, -Ncheck=extern,macro.
Example:
% lint -Ncheck=%all,no%macro |
performs all checks except macro checks.
Turns on enhanced lint mode by specifying the level of enhanced lint analysis for reporting problems. This option allows you to control the amount of detected errors. The higher the level, the longer the verification time. n is a number: 1, 2, 3, or 4. There is no default. If you do not specify -Nlevel, lint uses its basic analysis mode. If you specify -Nlevel without an argument, lint sets -Nlevel=4.
See 4.2 Using lint for an explanation of basic and enhanced lint modes.
Analyzes single procedures. Reports unconditional errors that occur on some program execution paths. Does not do global data and control flow analysis.
Analyzes the whole program, including global data and control flow. Reports unconditional errors that occur on some program execution paths.
Analyzes the whole program, including constant propagation, cases when constants are used as actual arguments, as well as the analysis performed under -Nlevel=2.
Verification of a C program at this analysis level takes two to four times longer then at the preceding level. The extra time is required because lint assumes partial interpretation of the program by creating sets of possible values for program variables. These sets of variables are created on the basis of constants and conditional statements that contain constant operands available in the program. The sets form the basis for creating other sets (a form of constant propagation). Sets received as the result of the analysis are evaluated for correctness according to the following algorithm:
If a correct value exists among all possible values of an object, then that correct value is used as the basis for further propagation; otherwise an error is diagnosed.
Analyzes the whole program, and reports conditional errors that could occur when certain program execution paths are used, as well as the analysis performed under -Nlevel=3.
At this analysis level, there are additional diagnostic messages. The analysis algorithm generally corresponds to the analysis algorithm of -Nlevel=3 with the exception that any invalid values now generate an error message. The amount of time required for analysis at this level can increase as much as two orders (about 20 to 100 time more slowly). In this case the extra time required is directly proportional to the program complexity as characterized by recursion, conditional statements etc. As a result of this, it may be difficult to use this level of analysis for a program that exceeds 100,000 lines.
Suppresses checks for compatibility with the default lint standard C library.
Causes lint to create a lint library with the name llib-lx.ln. This library is created from all the .ln files that lint used in its second pass. The -c option nullifies any use of the -o option. To produce a llib-lx.ln without extraneous messages, you can use the-x option. The -v option is useful if the source file(s) for the lint library are just external interfaces. The lint library produced can be used later if lint is invoked with -lx.
By default, you create libraries in lint’s basic format. If you use lint’s enhanced mode, the library created will be in enhanced format, and can only be used in enhanced mode.
Enables certain messages relating to portability issues.
Write a .ln file to file, for use by cxref(1). This option disables the enhanced mode, if it is switched on.
Produce simple diagnostics with "warning:" or "error:" prefixes. By default lint buffers some messages to produce compound output.
Suppresses certain messages. Refer to Table 4–8. This option is suitable for running lint on a subset of files of a larger program.
Writes the product name and releases to standard error.
Suppresses certain messages. Refer to Table 4–8.
Write a .ln file to file, for use by cflow(1). This option disables the enhanced mode, if it is switched on.
Accepts C++-style comments. In particular, // can be used to indicate the start of a comment. a can be either yes or no. The default is -XCC=no. Specifying -XCC is equivalent to specifying -XCC=yes.
You only need to use this option if you use -xc99=none. Under -xc99=all (the default), lint accepts comments which are indicated by //.
where l is one of any, basic, weak, layout, strict, std, or strong. See Table B–11 for a detailed explanation of the different levels of disambiguation.
If you do not specify -Xalias_level, the default of the flag is -Xalias_level=any. This means that there is no type-based alias-analysis. If you specify -Xalias_level but do not supply a level, the default is -Xalias_level=layout.
Be sure to run lint at a level of disambiguation that is no more strict than the level at which you ran the compiler. If you run lint at a level of disambiguation that is more strict than the level at which you compiled, the results will be difficult to interpret and possibly misleading.
See 4.6.3 lint Filters for a detailed explanation of disambiguation as well as a list of pragmas designed to help with disambiguation.
(Solaris Operating System) Deprecated. Do not use. See 4.3.25 -m32|-m64
(Solaris Operating System) Deprecated. Do not use. See 4.3.25 -m32|-m64
The -Xc99 flag controls compiler recognition of the implemented features from the C99 standard (ISO/IEC 9899:1999, Programming Language -C).
o can be one of the following: all, none.
-Xc99=none turns off recognition of C99 features. -Xc99=all turns on recognition of supported C99 features.
Specifying -Xc99 without any arguments is the same as -Xc99=all.
Though the compiler support-level defaults to the features of C99 listed in Table C–6 , the standard headers provided by Solaris software in /usr/include do not yet conform with the 1999 ISO/IEC C standard. If you encounter error messages, try using -Xc99=none to obtain the 1990 ISO/IEC C standard behavior for these headers.
(SPARC) Directs lint to recognize #pragma MP directives. a can be either yes or no. The default is -Xexplicitpar=no. Specifying -Xexplicitpar is equivalent to specifying -Xexplicitpar=yes.
Keeps temporary files created during linting instead of deleting them automatically. a can be either yes or no. The default is -Xkeeptmp=no. Specifying -Xkeeptmp is equivalent to specifying -Xkeeptmp=yes.
Sets the directory for temporary files to dir. Without this option, temporary files go into /tmp.
Reports the execution time for each lint pass. a can be either yes or no. The default is -Xtime=no. Specifying -Xtime is equivalent to specifying -Xtime=yes.
Issues warnings for the differences between K&R C and Sun ISO C. a can be either yes or no. The default is -Xtransition=no. Specifying -Xtransition is equivalent to specifying -Xtransition=yes.
This option enables recognition of string literals of the form U"ASCII_string" as an array of unsigned short int. The default is -Xustr=no which disables compiler recognition of U"ASCII_string string literals. "-Xustr=ascii_utf16_ushort enables compiler recognition of U"ASCII_string" string literals.
Suppresses certain messages. Refer to Table 4–8.
Treats every .c file named on the command line as if it begins with the directive /* LINTLIBRARY */ or the annotation NOTE(LINTLIBRARY). A lint library is normally created using the /* LINTLIBRARY */ directive or the NOTE(LINTLIBRARY) annotation.
Most of lint’s messages are simple, one-line statements printed for each occurrence of the problem they diagnose. Errors detected in included files are reported multiple times by the compiler, but only once by lint, no matter how many times the file is included in other source files. Compound messages are issued for inconsistencies across files and, in a few cases, for problems within them as well. A single message describes every occurrence of the problem in the file or files being checked. When use of a lint filter (see 4.6.2 lint Libraries) requires that a message be printed for each occurrence, compound diagnostics can be converted to the simple type by invoking lint with the -s option.
lint’s messages are written to stderr.
You can use several lint options to suppress lint diagnostic messages. Messages can be suppressed with the -erroff option, followed by one or more tags. These mnemonic tags can be displayed with the -errtags=yes option.
The following table lists the options that suppress lint messages.
Table 4–8 lint Options to Suppress Messages
Option |
Messages Suppressed |
---|---|
-a |
assignment causes implicit narrowing conversion conversion to larger integral type may sign-extend incorrectly |
-b |
statement not reached (unreachable break and empty statements) |
-h |
assignment operator "=" found where equality operator "==" was expected constant operand to op: "!" fallthrough on case statements pointer cast may result in improper alignment precedence confusion possible; parenthesize statement has no consequent: if statement has no consequent: else |
-m |
declared global, could be static |
-erroff=tag |
One or more lint messages specified by tag |
-u |
name defined but never used name used but not defined |
-v |
arguments unused in function |
-x |
name declared but never used or defined |
The lint program can, with certain options, show precise source file lines with pointers to the line position where the error occurred. The option enabling this feature is -errfmt=f. Under this option, lint provides the following information:
Source line(s) and position(s)
Macro unfolding
Error-prone stack(s)
For example, the following program, Test1.c, contains an error.
1 #include <string.h> 2 static void cpv(char *s, char* v, unsigned n) 3 { int i; 4 for (i=0; i<=n; i++){ 5 *v++ = *s++;} 6 } 7 void main(int argc, char* argv[]) 8 { 9 if (argc != 0){ 10 cpv(argv[0], argc, strlen(argv[0]));} 11} |
Using lint on Test1.c with the option:
% lint -errfmt=src -Nlevel=2 Test1.c |
produces the following output:
|static void cpv(char *s, char* v, unsigned n) | ^ line 2, Test1.c | | cpv(argv[0], argc, strlen(argv[0])); | ^ line 10, Test1.c warning: improper pointer/integer combination: arg #2 | |static void cpv(char *s, char* v, unsigned n) | ^ line 2, Test1.c | |cpv(argv[0], argc, strlen(argv[0])); | ^ line 10, Test1.c | | *v++ = *s++; | ^ line 5, Test1.c warning:use of a pointer produced in a questionable way v defined at Test1.c(2) ::Test1.c(5) call stack: main() , Test1.c(10) cpv() , Test1.c(5) |
The first warning indicates two source lines that are contradictory. The second warning shows the call stack, with the control flow leading to the error.
Another program, Test2.c, contains a different error:
1 #define AA(b) AR[b+l] 2 #define B(c,d) c+AA(d) 3 4 int x=0; 5 6 int AR[10]={1,2,3,4,5,6,77,88,99,0}; 7 8 main() 9 { 10 int y=-5, z=5; 11 return B(y,z); 12 } |
Using lint on Test2.c with the option:
% lint -errfmt=macro Test2.c |
produces the following output, showing the steps of macro substitution:
The following predefinitions are valid in all modes:
__SunOS (Solaris)
__SunOS_OSN_N (Solaris)
__amd64 (x86 with -m64)
__gnu__linux (linux)
__linux (linux)
__linux__ (linux)
linux (x86, linux)
These predefinitions are not valid in -Xc mode:
lint directives in the form of /*...*/ are supported for existing annotations, but will not be supported for future annotations. Directives in the form of source code annotations, NOTE(...), are recommended for all annotations.
Specify lint directives in the form of source code annotations by including the file note.h, for example:
#include <note.h>
Lint shares the Source Code Annotations scheme with several other tools. When you install the Sun C compiler, you also automatically install the file /usr/lib/note/SUNW_SPRO-lint, which contains the names of all the annotations that LockLint understands. However, the Sun C source code checker, lint, also checks all the files in /usr/lib/note and /opt/SUNWspro/prod/lib/note for all valid annotations.
You may specify a location other than /usr/lib/note by setting the environment variable NOTEPATH, as in:
setenv NOTEPATH $NOTEPATH:other_location |
The following table lists the lint directives along with their actions.
Table 4–9 The lint Directives
This section provides reference information on lint, including checks performed by lint, lint libraries, and lint filters.
lint-specific diagnostics are issued for three broad categories of conditions: inconsistent use, nonportable code, and questionable constructs. In this section, we review examples of lint’s behavior in each of these areas, and suggest possible responses to the issues they raise.
Inconsistent use of variables, arguments, and functions is checked within files as well as across them. Generally speaking, the same checks are performed for prototype uses, declarations, and parameters as lint checks for old-style functions. If your program does not use function prototypes, lint checks the number and types of parameters in each call to a function more strictly than the compiler. lint also identifies mismatches of conversion specifications and arguments in [fs]printf() and [fs]scanf() control strings.
Examples:
Within files, lint flags non-void functions that “fall off the bottom” without returning a value to the invoking function. In the past, programmers often indicated that a function was not meant to return a value by omitting the return type: fun() {}. That convention means nothing to the compiler, which regards fun() as having the return type int. Declare the function with the return type void to eliminate the problem.
Across files, lint detects cases where a non-void function does not return a value, yet is used for its value in an expression—and the opposite problem, a function returning a value that is sometimes or always ignored in subsequent calls. When the value is always ignored, it may indicate an inefficiency in the function definition. When it is sometimes ignored, it’s probably bad style (typically, not testing for error conditions). If you need not check the return values of string functions like strcat(), strcpy(), and sprintf(), or output functions like printf() and putchar(), cast the offending calls to void.
lint identifies variables or functions that are declared but not used or defined; used, but not defined; or defined, but not used. When lint is applied to some, but not all files of a collection to be loaded together, it produces error messages about functions and variables that are:
Declared in those files, but defined or used elsewhere
Used in those files, but defined elsewhere
Defined in those files, but used elsewhere
Invoke the-x option to suppress the first complaint, -u to suppress the latter two.
Some nonportable code is flagged by lint in its default behavior, and a few more cases are diagnosed when lint is invoked with -p or -Xc. The latter causes lint to check for constructs that do not conform to the ISO C standard. For the messages issued under -p and -Xc, see 4.6.2 lint Libraries.
Examples:
In some C language implementations, character variables that are not explicitly declared signed or unsigned are treated as signed quantities with a range typically from -128 to 127. In other implementations, they are treated as nonnegative quantities with a range typically from 0 to 255. So the test:
char c; c = getchar(); if (c == EOF) ... |
where EOF has the value -1, always fails on machines where character variables take on nonnegative values. lint invoked with -p checks all comparisons that imply a plain char may have a negative value. However, declaring c as a signed char in the above example eliminates the diagnostic, not the problem. That’s because getchar() must return all possible characters and a distinct EOF value, so a char cannot store its value. We cite this example, perhaps the most common one arising from implementation-defined sign-extension, to show how a thoughtful application of lint’s portability option can help you discover bugs not related to portability. In any case, declare c as an int.
A similar issue arises with bit-fields. When constant values are assigned to bit-fields, the field may be too small to hold the value. On a machine that treats bit-fields of type int as unsigned quantities, the values allowed for int x:3 range from 0 to 7, whereas on machines that treat them as signed quantities, they range from -4 to 3. However, a three-bit field declared type int cannot hold the value 4 on the latter machines. lint invoked with -p flags all bit-field types other than unsigned int or signed int. These are the only portable bit-field types. The compiler supports int, char, short, and long bit-field types that may be unsigned, signed, or plain. It also supports the enum bit-field type.
Bugs can arise when a larger-sized type is assigned to a smaller-sized type. If significant bits are truncated, accuracy is lost:
short s; long l; s = l; |
lint flags all such assignments by default; the diagnostic can be suppressed by invoking the -a option. Bear in mind that you may be suppressing other diagnostics when you invoke lint with this or any other option. Check the list in 4.6.2 lint Libraries for the options that suppress more than one diagnostic.
A cast of a pointer to one object type to a pointer to an object type with stricter alignment requirements may not be portable. lint flags:
int *fun(y) char *y; { return(int *)y; } |
because, on most machines, an int cannot start on an arbitrary byte boundary, whereas a char can. You can suppress the diagnostic by invoking lint with -h, although, again, you may be disabling other messages. Better still, eliminate the problem by using the generic pointer void *.
ISO C leaves the order of evaluation of complicated expressions undefined. That is, when function calls, nested assignment statements, or the increment and decrement operators cause side effects when a variable is changed as a by-product of the evaluation of an expression, the order in which the side effects take place is highly machine-dependent. By default, lint flags any variable changed by a side effect and used elsewhere in the same expression:
int a[10]; main() { int i = 1; a[i++] = i; } |
In this example, the value of a[1] may be 1 if one compiler is used, 2 if another. The bitwise logical operator & can give rise to this diagnostic when it is mistakenly used in place of the logical operator &&:
if ((c = getchar()) != EOF & c != ’0’) |
lint flags a miscellany of legal constructs that may not represent what the programmer intended. Examples:
An unsigned variable always has a nonnegative value. So the test:
unsigned x; if (x < 0) ... |
always fails. The test:
unsigned x; if (x > 0) ... |
is equivalent to:
if (x != 0) ... |
This may not be the intended action. lint flags questionable comparisons of unsigned variables with negative constants or 0. To compare an unsigned variable to the bit pattern of a negative number, cast it to unsigned:
if (u == (unsigned) -1) ... |
Or use the U suffix:
if (u == -1U) ... |
lint flags expressions without side effects that are used in a context where side effects are expected—that is, where the expression may not represent what the programmer intends. It issues an additional warning whenever the equality operator is found where the assignment operator is expected—that is, where a side effect is expected:
int fun() { int a, b, x, y; (a = x) && (b == y); } |
lint cautions you to parenthesize expressions that mix both the logical and bitwise operators (specifically, &, |, ^, <<, >>), where misunderstanding of operator precedence may lead to incorrect results. Because the precedence of bitwise &, for example, falls below logical ==, the expression:
if (x & a == 0) ... |
is evaluated as:
if (x & (a == 0)) ... |
which is most likely not what you intended. Invoking lint with -h disables the diagnostic.
You can use lint libraries to check your program for compatibility with the library functions you have called in it—the declaration of the function return type, the number and types of arguments the function expects, and so on. The standard lint libraries correspond to libraries supplied by the C compilation system, and generally are stored in a standard place on your system. By convention, lint libraries have names of the form llib-lx.ln.
The lint standard C library, llib-lc.ln, is appended to the lint command line by default; checks for compatibility with it can be suppressed by invoking the -n option. Other lint libraries are accessed as arguments to -l. That is:
% lint -lx file1.c file2.c |
directs lint to check the usage of functions and variables in file1.c and file2.c for compatibility with the lint library llib-lx.ln. The library file, which consists only of definitions, is processed exactly as are ordinary source files and ordinary .ln files, except that functions and variables used inconsistently in the library file, or defined in the library file but not used in the source files, elicit no complaints.
To create your own lint library, insert the directive NOTE(LINTLIBRARY) at the head of a C source file, then invoke lint for that file with the -o option and the library name given to -l:
% lint -ox file1.c file2.c |
causes only definitions in the source files headed by NOTE(LINTLIBRARY) to be written to the file llib-lx.ln. (Note the analogy of lint -o to cc -o.) A library can be created from a file of function prototype declarations in the same way, except that both NOTE(LINTLIBRARY) and NOTE(PROTOLIB(n))must be inserted at the head of the declarations file. If n is 1, prototype declarations are written to a library .ln file just as are old-style definitions. If n is 0, the default, the process is cancelled. Invoking lint with -y is another way of creating a lint library. The command line:
% lint -y -ox file1.c file2.c |
causes each source file named on that line to be treated as if it begins with NOTE(LINTLIBRARY), and only its definitions to be written to llib-lx.ln.
By default, lint searches for lint libraries in the standard place. To direct lint to search for a lint library in a directory other than the standard place, specify the path of the directory with the -L option:
% lint -Ldir -lx file1.c file2.c |
In enhanced mode, lint produces .ln files which store additional information than .ln files produced in basic mode. In enhanced mode, lint can read and understand all .ln files generated by either basic or enhanced lint modes. In basic mode, lint can read and understand .ln files generated only using basic lint mode.
By default, lint uses libraries from the /usr/lib directory. These libraries are in the basic lint format. You can run a makefile once, and create enhanced lint libraries in a new format, which will enable enhanced lint to work more effectively. To run the makefile and create the new libraries, enter the command:
% cd /opt/SUNWspro/prod/src/lintlib; make |
where /opt/SUNWspro/prod is the installation directory. After the makefile is run, lint uses the new libraries in enhanced mode, instead of the libraries in the /usr/lib directory.
The specified directory is searched before the standard place.
A lint filter is a project-specific post-processor that typically uses an awk script or similar program to read the output of lint and discard messages that your project has deemed as not identifying real problems—string functions, for instance, returning values that are sometimes or always ignored. lint filters generate customized diagnostic reports when lint options and directives do not provide sufficient control over output.
Two options to lint are particularly useful in developing a filter:
Invoking lint with -s causes compound diagnostics to be converted into simple, one-line messages issued for each occurrence of the problem diagnosed. The easily parsed message format is suitable for analysis by an awk script.
Invoking lint with -k causes certain comments you have written in the source file to be printed in output, and can be useful both in documenting project decisions and specifying the post-processor’s behavior. In the latter instance, if the comment identifies an expected lint message, and the reported message is the same, the message can be filtered out. To use -k, insert on the line preceding the code you wish to comment the NOTE(LINTED(msg))directive, where msg refers to the comment to be printed when lint is invoked with -k.
Refer to the list of directives in Table 4–9 for an explanation of what lint does when -k is not invoked for a file containing NOTE(LINTED(msg)).