第 8 章 cscope: 対話的な C プログラムの検査. Cscope は、 プログラム C、lex、または yacc ソースファイル内のコードの特定の要素を探し出す対話型プログラムです。 cscope ブラウザを使用すると、従来のエディタよりも効率的にソースファイルを検索、編集できます。 。これは、cscope が関数. Get notifications on updates for this project. Get the SourceForge newsletter. Get newsletters and notices that include site news, special offers and exclusive discounts about IT.
- Categories
- Top types
- Audio & home theatre
- Cameras & camcorders
- Computer cables
- Computer components
- Computers
- Data input devices
- Data storage
- Networking
- Print & Scan
- Projectors
- Smart wearables
- Software
- Telecom & navigation
- TVs & monitors
- Warranty & support
- other →
- Top brands
- Acer
- AEG
- Aeg-Electrolux
- Canon
- Electrolux
- ESAB
- HP
- LG
- Miller
- Nikon
- Panasonic
- Philips
- Samsung
- Sony
- Texas Instruments
- other →
- Top types
- Infotainment
- Musical instruments
- Video games & consoles
- other →
- Top brands
- Acer
- AEG
- Asus
- Electrolux
- ESAB
- HP
- LG
- Panasonic
- Philips
- Progress
- Samsung
- Sharp
- Sony
- ZANKER
- Zoppas
- other →
- Top types
- Binding machines
- Boards
- Calculators
- Correction media
- Desk accessories & supplies
- Drawing supplies
- Equipment cleansing kit
- Folders, binders & indexes
- Laminators
- Mail supplies
- Paper cutters
- Sorters
- Storage accessories for office machines
- Typewriters
- Writing instruments
- other →
- Top brands
- Bosch
- Canon
- Casio
- Craftsman
- Epson
- Garmin
- GE
- HP
- KitchenAid
- LG
- Panasonic
- Philips
- Samsung
- Sharp
- Texas Instruments
- other →
- Top types
- Bedding & linens
- Cleaning & disinfecting
- Do-It-Yourself tools
- Domestic appliances
- Home décor
- Home furniture
- Home security & automation
- Kitchen & houseware accessories
- Kitchenware
- Lighting
- other →
- Top brands
- AEG
- Aeg-Electrolux
- Bauknecht
- Bosch
- Electrolux
- HP
- Indesit
- LG
- Panasonic
- Philips
- Progress
- Samsung
- Sony
- Whirlpool
- Zanussi
- other →
- Top types
- Bags & cases
- Children carnival costumes
- Clothing care
- Clothing hangers
- Dry cleaners
- Fabric shavers
- Jewelry cleaning machines
- Men's clothing
- Tie holders
- Ultrasonic cleaning equipment
- Watches
- Women's clothing
- other →
- Top brands
- Casio
- Garmin
- Hotpoint
- Huawei
- Indesit
- LG
- Mitsubishi Electric
- Omega
- Philips
- Radio Shack
- Seiko
- Sony
- Uniden
- V7
- Whirlpool
- other →
- Top types
- Air Handlers
- Boom Lifts
- Compact Excavator
- Elevators
- Excavators
- Finishers
- Front End Loaders
- Noise Reduction Machine
- Oxygen Equipment
- Robotics
- Scrubber
- Spreader
- Tractor
- Trash Compactor
- Welding System
- other →
- Top brands
- AEG
- Aeg-Electrolux
- Canon
- Electrolux
- ESAB
- HP
- LG
- Miller
- Nikon
- Panasonic
- Philips
- Samsung
- Sony
- Texas Instruments
- Whirlpool
- other →
- Top types
- Blood pressure units
- Electric toothbrushes
- Epilators
- Feminine hygiene products
- Foot baths
- Hair trimmers & clippers
- Makeup & manicure cases
- Men's shavers
- Personal paper products
- Personal scales
- Shaver accessories
- Skin care
- Solariums
- Teeth care
- Women's shavers
- other →
- Top brands
- AEG
- Aeg-Electrolux
- Bosch
- Canon
- Casio
- Electrolux
- Garmin
- LG
- Panasonic
- Philips
- Samsung
- Sony
- Whirlpool
- Yamaha
- Zanussi
- other →
- Top types
- Hot beverage supplies
- other →
- Top brands
- other →
- Top types
- Cars
- Electric scooters
- Motor vehicle accessories & components
- Motor vehicle electronics
- Motorcycles
- Motorhomes
- Offroad Vehicle
- Scooters
- Utility Vehicle
- other →
- Top brands
- AEG
- Aeg-Electrolux
- Canon
- Casio
- Electrolux
- Garmin
- LG
- Miller
- Panasonic
- Philips
- Samsung
- Sony
- Volvo
- Yamaha
- Zanussi
- other →
- Top types
- Baby bathing & potting
- Baby furniture
- Baby safety
- Baby sleeping & bedding
- Baby travel
- Feeding, diapering & nursing
- Toys & accessories
- other →
- Top brands
- AEG
- Canon
- Electrolux
- Garmin
- HP
- LG
- Miller
- Panasonic
- Philips
- Samsung
- Sony
- Volvo
- Whirlpool
- Yamaha
- Zanussi
- other →
- Top types
- Bicycles & accessories
- Bubble machines
- Camping, tourism & outdoor
- Fitness, gymnastics & weight training
- Martial arts equipment
- Skateboarding & skating
- Smoke machines
- Sport protective gear
- Target & table games
- Water sports equipment
- Winter sports equipment
- other →
- Top brands
- Craftsman
- Daikin
- Emerson
- Epson
- Frigidaire
- Harbor Freight Tools
- HP
- Miele
- Miller
- Omega
- Panasonic
- Philips
- Samsung
- Weider
- Yamaha
- other →
- Top types
- Pet hair clippers
- other →
- Top brands
- Andis
- other →
- Top types
- Home building and Decor
- Kitchen appliances
- Other
- Science and Education
- other →
- Top brands
- other →
- Top types
- Pill Reminder Device
- Stairlifts
- other →
- Top brands
- Alber
- Bruno
- E-PIL
- Minivator
- Savaria
- other →
cscope is an interactive program that locates specified elements of code in C, lex, or yacc source files. With cscope,you can search and edit your source files more efficiently than you couldwith a typical editor. That’s because cscope supportsfunction calls—when a function is being called, when it is doing thecalling—as well as C language identifiers and keywords.
This chapter is a tutorial on the cscope browserprovided with this release.
Note – The cscope program has not yet been updated to understand codeswritten for the 1999 ISO/IEC C standard. For example, it does not yet recognizethe new keywords introduced in the 1999 ISO/IEC C standard.
When cscope iscalled for a set of C, lex, or yacc sourcefiles, it builds a symbol cross-reference table for the functions, functioncalls, macros, variables, and preprocessor symbols in those files. You canthen query that table about the locations of symbols you specify. First, itpresents a menu and asks you to choose the type of search you would like tohave performed. You may, for instance, want cscope to findall the functions that call a specified function.
When cscope has completed this search, it printsa list. Each list entry contains the name of the file, the number of the line,and the text of the line in which cscope has found thespecified code. In our case, the list also includes the names of the functionsthat call the specified function. You now have the option of requesting anothersearch or examining one of the listed lines with the editor. If you choosethe latter, cscope invokes the editor for the file in whichthe line appears, with the cursor on that line. You can now view the codein context and, if you wish, edit the file as any other file. You can thenreturn to the menu from the editor to request a new search.
Because the procedure you follow depends on the task at hand, thereis no single set of instructions for using cscope. Foran extended example of its use, review the cscope sessiondescribed in the next section. It shows how you can locate a bug in a programwithout learning all the code.
Suppose you are given responsibilityfor maintaining the program prog. You are told that anerror message, out of storage, sometimes appears just as the program startsup. Now you want to use cscope to locate the parts of thecode that are generating the message. Here is how you do it.
8.2.1 Step 1: Set Up the Environment
cscope isa screen-oriented tool that can only be used on terminals listed in the TerminalInformation Utilities (terminfo) database. Be sure youhave set the TERM environment variable to yourterminal type so that cscope can verify that it is listedin the terminfo database. If you have not done so, assigna value to TERM and export it to the shell as follows:
In a Bourne shell, type:
In a C shell, type:
You may now want to assign a value to the EDITOR environment variable. By default, cscope invokesthe vieditor.(The examples in this chapter illustrate vi usage.) Ifyou prefer not to use vi, set the EDITOR environmentvariable to the editor of your choice and export EDITOR,as follows:
In a Bourne shell, type:
In a C shell, type:
You may have to write an interface between cscope andyour editor. For details, see 8.2.9 Command-Line Syntax for Editors.
If you want to use cscope only for browsing (withoutediting), you can set the VIEWER environment variable to pg and export VIEWER. cscope willthen invoke pg instead of vi.
An environment variable called VPATH can be set to specifydirectories to be searched for source files. See 8.2.6 View Paths.
8.2.2 Step 2: Invoke the cscope Program
By default, cscope buildsa symbol cross-reference table for all the C, lex, and yacc source files in the current directory, and for any includedheader files in the current directory or the standard place. So, if all thesource files for the program to be browsed are in the current directory, andif its header files are there or in the standard place, invoke cscope withoutarguments:
To browse through selected source files, invoke cscope withthe names of those files as arguments:
For other ways to invoke cscope, see 8.2.5 Command-Line Options.
cscope builds the symbol cross-reference table thefirst time it is used on the source files for the program to be browsed. Bydefault, the table is stored in the file cscope.out inthe current directory. On a subsequent invocation, cscope rebuildsthe cross-reference only if a source file has been modified or the list ofsource files is different. When the cross-reference is rebuilt, the data forthe unchanged files is copied from the old cross-reference, which makes rebuildingfaster than the initial build, and reduces startup time for subsequent invocations.
8.2.3 Step 3: Locate the Code
Now let’s returnto the task we undertook at the beginning of this section: to identify theproblem that is causing the error message out of storage to be printed. Youhave invoked cscope, the cross-reference table has beenbuilt. The cscope menu of tasks appears on the screen.
The cscope Menu of Tasks:
Press the Return key to move the cursor down the screen (with wraparoundat the bottom of the display), and ^p (Control-p) to movethe cursor up; or use the up (ua) and down (da)arrow keys. You can manipulate the menu and perform other tasks with the followingsingle-key commands:
Table 8–1 cscope Menu Manipulation CommandsTab | Move to the next input field. |
Return | Move to the next input field. |
^n | Move to the next input field. |
^p | Move to the previous input field. |
^y | Search with the last text typed. |
^b | Move to the previous input field and search pattern. |
^f | Move to the next input field and search pattern. |
^c | Toggle ignore/use letter case when searching. For example, a searchfor FILE matches file and File whenignoring the letter case. |
^r | Rebuild cross-reference. |
! | Start an interactive shell. Type ^d to returnto cscope. |
^l | Redraw the screen. |
? | Display the list of commands. |
^d | Exit cscope. |
If the first character of the text for which you are searching matchesone of these commands, you can escape the command by entering a (backslash)before the character.
Now move the cursor to the fifth menu item, Find this textstring, enter the text out of storage, and press the Return key.
cscope Function: Requesting a Search for a Text String:
Follow the same procedure to perform any other task listed inthe menu except the sixth, Changethistextstring. Because this task is slightly morecomplex than the others, there is a different procedure for performing it.For a description of how to change a text string, see 8.2.8 Examples.
cscope searches for the specified text, finds oneline that contains it, and reports its finding.
cscope Function: Listing Lines Containing the TextString:
After cscope shows you the results of a successfulsearch, you have several options. You may want to change one of the linesor examine the code surrounding it in the editor. Or, if cscope hasfound so many lines that a list of them does not fit on the screen at once,you may want to look at the next part of the list. The following table showsthe commands available after cscope has found the specifiedtext:
Table 8–2 Commands for Use After an Initial Search1 -9 | Edit the file referenced by this line. The number you type correspondsto an item in the list of lines printed by cscope. |
Space | Display the next set of matching lines. |
+ | Display the next set of matching lines. |
^v | Display the next set of matching lines. |
-- | Display the previous set of matching lines. |
^e | Edit the displayed files in order. |
> | Append the list of lines being displayed to a file. |
| | Pipe all lines to a shell command. |
Again, if the first character of the text for which you are searchingmatches one of these commands, you can escape the command by entering a backslashbefore the character.
Now examine the code around the newly found line. Enter 1 (thenumber of the line in the list). The editor is invoked with the file alloc.c with the cursor at the beginning of line 63 of alloc.c.
cscope Function: Examining a Line of Code:
You can see that the error message is generated when the variable p is NULL. To determine how an argument passedto alloctest() could have been NULL,you must first identify the functions that call alloctest().
Exit the editor by using normal quit conventions. You are returned tothe menu of tasks. Now type alloctest after the fourthitem, Find functions calling this function.
cscope Function: Requesting a List of Functions ThatCall alloctest():
cscope finds and lists three such functions.
cscope Function: Listing FunctionsThat Call alloctest():
Now you want to know which functions call mymalloc(). cscope finds ten such functions. It lists nine of them on the screenand instructs you to press the space bar to see the rest of the list.
cscope Function: Listing FunctionsThat Call mymalloc():
Because you know that the error message out of storage is generatedat the beginning of the program, you can guess that the problem may have occurredin the function dispinit() (display initialization).
To view dispinit(), the seventh function on the list,type 7.
cscope Function: Viewing dispinit() inthe Editor:
mymalloc() failed because it was called either witha very large number or a negative number. By examining the possible valuesof FLDLINE and REFLINE, you can seethat there are situations in which the value of mdisprefs isnegative, that is, in which you are trying to call mymalloc() witha negative number.
8.2.4 Step 4: Edit the Code
On a windowing terminal,you may have multiple windows of arbitrary size. The error message out ofstorage might have appeared as a result of running prog ina window with too few lines. In other words, that may have been one of thesituations in which mymalloc() was called with a negativenumber. Now you want to be sure that when the program aborts in this situationin the future, it does so after printing the more meaningful error messagescreen too small. Edit the function dispinit() as follows.
cscope Function: Correcting the Problem:
You have fixed the problem we began investigating at the beginning ofthis section. Now if prog is run in a window with too fewlines, it does not simply fail with the unedifying error message out of storage.Instead, it checks the window size and generates a more meaningful error messagebefore exiting.
8.2.5 Command-Line Options
As noted, cscope buildsa symbol cross-reference table for the C, lex, and sourcefiles in the current directory by default. That is,
is equivalent to:
We have also seen that you can browse through selected source filesby invoking cscope with the names of those files as arguments:
cscope provides command-line options with greaterflexibility in specifying source files to be included in the cross-reference.When you invoke cscope with the– s optionand any number of directory names (separated by commas):
cscope builds a cross-reference for all the sourcefiles in the specified directories as well as the current directory. To browsethrough all of the source files whose names are listed in file (filenames separated by spaces, tabs, or new-lines), invoke cscope withthe– i option and the name of the file containingthe list:
If your source files are in a directory tree, use the following commandsto browse through all of them:
If this option is selected, however, cscope ignoresany other files appearing on the command-line.
The– I option can be used for cscope inthe same way as the– I option to cc.See 2.14 How to Specify Include Files.
You can specify a cross-reference file other than the default cscope.out by invoking the– f option. This is usefulfor keeping separate symbol cross-reference files in the same directory. Youmay want to do this if two programs are in the same directory, but do notshare all the same files:
In this example, the source files for two programs, admin and delta, are in the same directory, but the programs consist of differentgroups of files. By specifying different symbol cross-reference files whenyou invoke cscope for each set of source files, the cross-referenceinformation for the two programs is kept separate.
You can use the– pn optionto specify that cscope display the path name, or part ofthe path name, of a file when it lists the results of a search. The numberyou give to– p stands for the last n elementsof the path name you want to be displayed. The default is 1,the name of the file itself. So if your current directory is home/common, the command:
causes cscope to display common/file1.c, common/file2.c, and so forth when it lists the results of a search.
If the program you want to browse contains a large number of sourcefiles, you can use the– b option, so that cscope stops after it has built a cross-reference; cscope doesnot display a menu of tasks. When you use cscope– b ina pipeline with the batch(1) command, cscope buildsthe cross-reference in the background:
Once the cross-reference is built, and as long as you have not changeda source file or the list of source files in the meantime, you need only specify:
for the cross-reference to be copied and the menu of tasks to be displayedin the normal way. You can use this sequence of commands when you want tocontinue working without having to wait for cscope to finishits initial processing.
The– d option instructs cscope notto update the symbol cross-reference. You can use it to save time if you aresure that no such changes have been made; cscope does notcheck the source files for changes.
Note – Use the – d option with care. If youspecify – d under the erroneous impression that yoursource files have not been changed, cscope refers to anoutdated symbol cross-reference in responding to your queries.
Check the cscope(1) man page for other command-lineoptions.
8.2.6 View Paths
As we have seen, cscope searches for source files in the current directory by default.When the environment variable VPATH is set, cscope searchesfor source files in directories that comprise your view path. A view pathis an ordered list of directories, each of which has the same directory structurebelow it.
For example, suppose you are part of a software project. There is an official set of source files in directories below /fs1/ofc.Each user has a home directory (/usr/you). If you makechanges to the software system, you may have copies of just those files youare changing in /usr/you/src/cmd/prog1. The official versionsof the entire program can be found in the directory /fs1/ofc/src/cmd/prog1.
Suppose you use cscope to browse through the threefiles that comprise prog1, namely, f1.c, f2.c, and f3.c. You would set VPATH to /usr/you and /fs1/ofc and export it, as in:
In a Bourne shell, type:
In a C shell, type:
You then make your current directory /usr/you/src/cmd/prog1,and invoke cscope:
The program locates all the files in the view path. In case duplicatesare found, cscope uses the file whose parent directoryappears earlier in VPATH. Thus, if f2.c isin your directory, and all three files are in the official directory, cscope examines f2.c from your directory, and f1.c and f3.c from the official directory.
The first directory in VPATH must be a prefix ofthe directory you will be working in, usually $HOME. Eachcolon-separated directory in VPATH must be absolute: itshould begin at /.
8.2.7 cscope and Editor Call Stacks
cscope and editor calls can be stacked. That is,when cscope puts you in the editor to view a referenceto a symbol and there is another reference of interest, you can invoke cscope again from within the editor to view the second reference withoutexiting the current invocation of either cscope or theeditor. You can then back up by exiting the most recent invocation with theappropriate cscope and editor commands.
8.2.8 Examples
This section presents examplesof how cscope can be used to perform three tasks: changinga constant to a preprocessor symbol, adding an argument to a function, andchanging the value of a variable. The first example demonstrates the procedurefor changing a text string, which differs slightly from the other tasks onthe cscope menu. That is, once you have entered the textstring to be changed, cscope prompts you for the new text,displays the lines containing the old text, and waits for you to specify whichof these lines you want it to change.
8.2.8.1 Changing a Constant to a Preprocessor Symbol
Suppose you want to change a constant, 100, to apreprocessor symbol, MAXSIZE. Select the sixth menu item, Change this text string, and enter 100.The 1 must be escaped with a backslash because it has aspecial meaning (item 1 on the menu) to cscope. Now pressReturn. cscope prompts you for the new text string. Type MAXSIZE.
cscope Function: Changing a Text String:
cscope displays the lines containing the specifiedtext string, and waits for you to select those in which you want the textto be changed.
cscope Function: Prompting for Lines to be Changed:
You know that the constant 100 in lines 1, 2, and3 of the list (lines 4, 26, and 8 of the listed source files) should be changedto MAXSIZE. You also know that 0100 in read.c and 100.0 in err.c (lines4 and 5 of the list) should not be changed. You select the lines you wantchanged with the following single-key commands:
Table 8–3 Commands for Selecting Lines to Be Changed1-9 | Mark or unmark the line to be changed. |
* | Mark or unmark all displayed lines to be changed. |
Space | Display the next set of lines. |
+ | Display the next set of lines. |
– | Display the previous set of lines. |
a | Mark all lines to be changed. |
^d | Change the marked lines and exit. |
Esc | Exit without changing the marked lines. |
In this case, enter 1, 2,and 3. The numbers you type are not printed on thescreen. Instead, cscope marks each list item you want tobe changed by printing a > (greater than) symbol afterits line number in the list.
cscope Function: Marking Lines to be Changed:
Now type ^d to change the selected lines. cscope displays the lines that have been changed and prompts you to continue.
cscope Function: Displaying Changed Lines of Text:
When you press Return in response to this prompt, cscope redrawsthe screen, restoring it to its state before you selected the lines to bechanged.
The next step is to add the #define for the new symbol MAXSIZE. Because the header file in which the #define isto appear is not among the files whose lines are displayed, you must escapeto the shell by typing !. The shell prompt appearsat the bottom of the screen. Then enter the editor and add the #define.
cscope Function: Exiting to the Shell:
To resume the cscope session, quit the editor andtype ^d to exit the shell.
8.2.8.2 Adding an Argument to a Function
Adding an argument to a function involves two steps: editing the functionitself and adding the new argument to every place in the code where the functionis called.
First, edit the function by using the second menu item, Findthis global definition. Next, find out where the function is called.Use the fourth menu item, Find functions calling this function,to obtain a list of all the functions that call it. With this list, you caneither invoke the editor for each line found by entering the list number ofthe line individually, or invoke the editor for all the lines automaticallyby typing ^e. Using cscope to makethis kind of change ensures that none of the functions you need to edit areoverlooked.
8.2.8.3 Changing the Value of a Variable
At times, you may want to see how a proposed change affects your code.
Suppose you want to change the value of a variable or preprocessor symbol.Before doing so, use the first menu item, Find this C symbol,to obtain a list of references that are affected. Then use the editor to examineeach one. This step helps you predict the overall effects of your proposedchange. Later, you can use cscope in the same way to verifythat your changes have been made.
8.2.9 Command-Line Syntax for Editors
cscope invokes the vieditor by default. You can override the default settingby assigning your preferred editor to the EDITOR environmentvariable and exporting EDITOR, as described in 8.2.1 Step 1: Set Up the Environment. However, cscope expects the editor it uses to have a command-line syntax of theform:
as does vi. If the editor you want to use does nothave this command-line syntax, you must write an interface between cscope and the editor.
Suppose you want to use ed. Because ed doesnot allow specification of a line number on the command-line, you cannot useit to view or edit files with cscope unless you write ashell script that contains the following line:
Let’s name the shell script myedit. Now setthe value of EDITOR toyour shell script and export EDITOR:
In a Bourne shell, type:
In a C shell, type:
When cscope invokes the editor for the list itemyou have specified, say, line 17 in main.c, it invokesyour shell script with the command-line:
myedit then discards the line number ($1)and calls ed correctly with the file name ($2).Of course, you are not moved automatically to line 17 of the file and mustexecute the appropriate ed commands to display and edit the line.
If you see the error message:
your terminal may not be listed in the Terminal Information Utilities(terminfo) database that is currently loaded. Make sureyou have assigned the correct value to TERM. If the messagereappears, try reloading the Terminal Information Utilities.
If this message is displayed:
set and export the TERM variable as described in 8.2.1 Step 1: Set Up the Environment.