diff --git a/FAQ/admin.sgml b/FAQ/admin.sgml index d5ebbdb0f7..9b8739ebd6 100644 --- a/FAQ/admin.sgml +++ b/FAQ/admin.sgml @@ -1,827 +1,827 @@ - + System Administration Where are the system start-up configuration files?

From 2.0.5R to 2.2.1R, the primary configuration file is /etc/sysconfig. All the options are to be specified in this file and other files such as and /etc/netstart just include it.

Look in the /etc/sysconfig file and change the value to match your system. This file is filled with comments to show what to put in there.

In post-2.2.1 and 3.0, /etc/sysconfig was renamed to a more self-describing file and the syntax cleaned up a bit in the process. /etc/netstart was also renamed to /etc/rc.network so that all files could be copied with a /usr/src/etc/rc* /etc command.

/etc/rc.local is here as always and may be used to start up additional local services like or set custom options.

The /etc/rc.serial is for serial port initialization (e.g. locking the port characteristics, and so on.).

The /etc/rc.i386 is for Intel-specifics settings, such as iBCS2 emulation or the PC system console configuration.

Starting with 2.1.0R, you can also have "local" startup files in a directory specified in /etc/sysconfig (or /etc/rc.conf): # Location of local startup files. local_startup=/usr/local/etc/rc.local.d

Each file ending in If you want to ensure a certain execution order without changing all the file names, you can use a scheme similar to the following with digits prepended to each file name to insure the ordering: 10news.sh 15httpd.sh 20ssh.sh

It can be seen as ugly (or SysV :-)) but it provides a simple and regular scheme for locally-added packages without resorting to magical editing of /etc/rc.local. Many of the ports/packages assume that /usr/local/etc/rc.d is a local startup directory. How do I add a user easily?

Use the command.

There is another package called ``<roberto@FreeBSD.ORG> about it. It is currently undergoing further development.

To remove the user again, use the command. How can I add my new hard disk to my FreeBSD system?

See the Disk Formatting Tutorial at - . I have a new removable drive, how do I use it?

Whether it's a removable drive like a ZIP or an EZ drive (or even a floppy, if you want to use it that way), or a new hard disk, once it's installed and recognized by the system, and you have your cartridge/floppy/whatever slotted in, things are pretty much the same for all devices.

If it's a ZIP drive or a floppy , you've already got a DOS filesystem on it, you can use a command like this: mount -t msdos /dev/fd0c /floppy

if it's a floppy, or this: mount -t msdos /dev/sd2s4 /zip

for a ZIP disk with the factory configuration.

For other disks, see how they're laid out using /stand/sysinstall.

The rest of the examples will be for a ZIP drive on sd2, the third SCSI disk.

Unless it's a floppy, or a removable you plan on sharing with other people, it's probably a better idea to stick a BSD file system on it. You'll get long filename support, at least a 2X improvement in performance, and a lot more stability. First, you need to redo the DOS-level partitions/filesystems. You can either use or /stand/sysinstall, or for a small drive that you don't want to bother with multiple operating system support on, just blow away the whole FAT partition table (slices) and just use the BSD partitioning: dd if=/dev/zero of=/dev/rsd2 count=2 disklabel -Brw sd2 auto

You can use disklabel or /stand/sysinstall to create multiple BSD partitions. You'll certainly want to do this if you're adding swap space on a fixed disk, but it's probably irrelevant on a removable drive like a ZIP.

Finally, create a new file system, this one's on our ZIP drive using the whole disk: newfs /dev/rsd2c

and mount it: mount /dev/sd2c /zip

and it's probably a good idea to add a line like this to so you can just type "mount /zip" in the future: /dev/sd2c /zip ffs rw,noauto 0 0 How do I mount a secondary DOS partition?

The secondary DOS partitions are found after ALL the primary partitions. For example, if you have an "E" partition as the second DOS partition on the second SCSI drive, you need to create the special files for "slice 5" in /dev, then mount /dev/sd1s5: # cd /dev # ./MAKEDEV sd1s5 # mount -t msdos /dev/sd1s5 /dos/e Can I mount other foreign filesystems under FreeBSD?

for more information.

Any other information on this subject would be appreciated. How can I use the NT loader to boot FreeBSD?

The general idea is that you copy the first sector of your native root FreeBSD partition into a file in the DOS/NT partition. Assuming you name that file something like c:\bootsect.bsd (inspired by c:\bootsect.dos), you can then edit the c:\boot.ini file to come up with something like this: [boot loader] timeout=30 default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS [operating systems] multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Windows NT" C:\BOOTSECT.BSD="FreeBSD" C:\="DOS"

This procedure assumes that DOS, NT, FreeBSD, or whatever have been installed into their respective fdisk partitions on the Mount a DOS-formatted floppy (if you've converted to NTFS) or the FAT partition, under, say, /mnt. dd if=/dev/rsd0a of=/mnt/bootsect.bsd bs=512 count=1

Reboot into DOS or NT. NTFS users copy the attrib -s -r c:\boot.ini

Edit to add the appropriate entries from the example attrib -r -s c:\boot.ini

If FreeBSD is booting from the MBR, restore it with the DOS `` How do I boot FreeBSD and Linux from LILO?

If you have FreeBSD and Linux on the same disk, just follow LILO's installation instructions for booting a non-Linux operating system. Very briefly, these are:

Boot Linux, and add the following lines to /etc/lilo.conf: other=/dev/hda2 table=/dev/hda label=FreeBSD (the above assumes that your FreeBSD slice is known to Linux as /dev/hda2; tailor to suit your setup). Then, run lilo as root and you should be done.

If FreeBSD resides on another disk, you need to add ``loader=/boot/chain.b'' to the LILO entry. For example: other=/dev/sdb4 table=/dev/sdb loader=/boot/chain.b label=FreeBSD

In some cases you may need to specify the BIOS drive number to the FreeBSD boot loader to successfully boot off the second disk. For example, if your FreeBSD SCSI disk is probed by BIOS as BIOS disk 1, at the FreeBSD boot loader prompt you need to specify: Boot: 1:sd(0,a)/kernel

On FreeBSD 2.2.5 and later, you can configure to automatically do this for you at boot time.

The is a good reference for FreeBSD and Linux interoperability issues. How do I boot FreeBSD and Linux using BootEasy?

Install LILO at the start of your Linux boot partition instead of in the Master Boot Record. You can then boot LILO from BootEasy.

If you're running Windows-95 and Linux this is recommended anyway, to make it simpler to get Linux booting again if you should need to reinstall Windows95 (which is a Jealous Operating System, and will bear no other Operating Systems in the Master Boot Record). Will a ``dangerously dedicated'' disk endanger my health?

Now, while this is certainly the common case for people coming from a PC background, those people coming more from a Unix background and who are going to setup a machine just to run FreeBSD and only FreeBSD, are more used to the classic Unix way where the operating system owns the entire disks, from the very first sector through the end. A true fdisk table isn't of any use in this case, the machine is running FreeBSD 24 hours per day, 7 days per week, no other operating system should ever be booted on it. So, if you select ``A)ll FreeBSD'' in sysinstall's fdisk editor, and answer the next question with ``No'', you'll get this mode. Note that this means the BSD bootstrap also forms the MBR for this drive, so there's no space left for anything like a boot manager. Don't ever try to install one, or you'll damage the BSD bootstrap.

So why it is called ``dangerous''? A disk in this mode doesn't contain what normal PC utilities would consider a valid fdisk table. Depending on how well they have been designed, they might complain at you once they are getting in contact with such a disk, or even worse, they might damage the BSD bootstrap without even asking or notifying you. Some kind of operating system that is in rather widespread use on PCs is known for this kind of user-unfriendliness (of course, it does this in the name of ``user-friendliness''). At least one Award BIOS that is for example used in HP Netservers (but not only there) is known to ignore any harddisk that doesn't have what it believes to be a valid fdisk table. When it comes to booting, it simply ignores such a disk drive, advances to the floppy drive, and barfs at you with just ``Read error''. Very impressive, eh? They probably also call this ``user-friendly'', who knows?

The advantages of this mode are: FreeBSD owns the entire disk, no need to waste several fictitious `tracks' for just nothing but a 1980-aged simplistic partitioning model enforcing some artificial and now rather nonsensical constraints on how this partitioning needs to be done. These constraints often lead to what might be the biggest headaches for OS installations on PCs, geometry mismatch hassles resulting out of two different, redundant ways how to store the partitioning information in the fdisk table. See the chapter about . In ``dangerously dedicated'' mode, the BSD bootstrap starts at sector 0, and this one is the only sector that always translates into the same C/H/S values, regardless of which `translation' your BIOS is using for your disk. Thus, you can also swap disks between systems/controllers that use a different translation scheme, without risking that they won't boot anymore.

To return a ``dangerously dedicated'' disk for normal PC use, there are basically two options. The first is, you write enough NULL bytes over the MBR to make any subsequent installation believe this to be a blank disk. You can do this for example with dd if=/dev/zero of=/dev/rsd0 count=15

Alternatively, the undocumented DOS ``feature'' fdisk /mbr

will to install a new master boot record as well, thus clobbering the BSD bootstrap. How can I add more swap space?

The best way is to increase the size of your swap partition, or take advantage of this convenient excuse to add another disk.

Adding swap onto a separate disk makes things faster than simply adding swap onto the same disk. As an example, if you are compiling source located on one disk, and the swap is on another disk, this is much faster than both swap and compile on the same disk. This is true for SCSI disks specifically.

IDE drives are not able to allow access to both drives on the same channel at the same time (FreeBSD doesn't support mode 4, so all IDE disk I/O is ``programmed''). I would still suggest putting your swap on a separate drive however. The drives are so cheap, it is not worth worrying about.

It is a really bad idea to locate your swap file over NFS unless you are running in a very fast networking environment, with a good server.

Here is an example for 64Mb vn-swap (/usr/swap0, though of course you can use any name that you want).

Make sure your kernel was built with the line pseudo-device vn 1 #Vnode driver (turns a file into a device)

in your config-file. The GENERIC kernel already contains this. create a vn-device cd /dev sh ./MAKEDEV vn0 create a swapfile (/usr/swap0) dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 enable the swap file in /etc/rc.conf swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. reboot the machine

To enable the swap file immediately, type vnconfig -ce /dev/vn0c /usr/swap0 swap I'm having problems setting up my printer.

Please have a look at the Handbook entry on printing. It should cover most of your problem. See the The keyboard mappings are wrong for my system.

The kbdcontrol program has an option to load a keyboard map file. Under /usr/share/syscons/keymaps are a number of map files. Choose the one relevant to your system and load it. kbdcontrol -l uk.iso

Both the /usr/share/syscons/keymaps and the .

This can be configured in /etc/sysconfig (or ). See the appropriate comments in this file.

In 2.0.5R and later, everything related to text fonts, keyboard mapping is in /usr/share/examples/syscons.

The following mappings are currently supported: Belgian ISO-8859-1 Brazilian 275 keyboard Codepage 850 Brazilian 275 keyboard ISO-8859-1 Danish Codepage 865 Danish ISO-8859-1 French ISO-8859-1 German Codepage 850 German ISO-8859-1 Italian ISO-8859-1 Japanese 106 Japanese 106x Latin American Norwegian ISO-8859-1 Polish ISO-8859-2 (programmer's) Russian Codepage 866 (alternative) Russian koi8-r (shift) Russian koi8-r Spanish ISO-8859-1 Swedish Codepage 850 Swedish ISO-8859-1 Swiss-German ISO-8859-1 United Kingdom Codepage 850 United Kingdom ISO-8859-1 United States of America ISO-8859-1 United States of America dvorak United States of America dvorakx I can't get user quotas to work properly.

Don't turn on quotas on '/', Put the quota file on the file system that the quotas are to be enforced on. ie: FS QUOTA FILE /usr /usr/admin/quotas /home /home/admin/quotas ... What's inappropriate about my ccd?

The symptom of this is: # ccdconfig -C ccdconfig: ioctl (CCDIOCSET): /dev/ccd0c: Inappropriate file type or format #

This usually happens when you are trying to concatenate the `c' partitions, which default to type `unused'. The ccd driver requires the underlying partition type to be FS_BSDFFS. Edit the disklabel of the disks you are trying to concatenate and change the types of partitions to `4.2BSD'. Why can't I edit the disklabel on my ccd?

The symptom of this is: # disklabel ccd0 (it prints something sensible here, so let's try to edit it) # disklabel -e ccd0 (edit, save, quit) disklabel: ioctl DIOCWDINFO: No disk label on disk; use "disklabel -r" to install initial label #

This is because the disklabel returned by ccd is actually a `fake' one that is not really on the disk. You can solve this problem by writing it back explicitly, as in: # disklabel ccd0 > /tmp/disklabel.tmp # disklabel -Rr ccd0 /tmp/disklabel.tmp # disklabel -e ccd0 (this will work now) Does FreeBSD support System V IPC primitives?

Yes, FreeBSD supports System V-style IPC. This includes shared memory, messages and semaphores. You need to add the following lines to your kernel config to enable them. options SYSVSHM options "SHMMAXPGS=64" # 256Kb of sharable memory options SYSVSEM # enable for semaphores options SYSVMSG # enable for messaging

Recompile and install.

How do I use sendmail for mail delivery with UUCP?

The sendmail configuration that ships with FreeBSD is suited for sites that connect directly to the Internet. Sites that wish to exchange their mail via UUCP must install another sendmail configuration file.

Tweaking /etc/sendmail.cf manually is considered something for purists. Sendmail version 8 comes with a new approach of generating config files via some preprocessing, where the actual hand-crafted configuration is on a higher abstraction level. You should use the configuration files under /usr/src/usr.sbin/sendmail/cf

If you didn't install your system with full sources, the sendmail config stuff has been broken out into a separate source distribution tarball just for you. Assuming you've got your CD-ROM mounted, do: cd /usr/src tar -xvzf /cdrom/dists/src/ssmailcf.aa

Don't panic, this is only a few hundred kilobytes in size. The file README in the cf directory can serve as a basic introduction to m4 configuration.

For UUCP delivery, you are best advised to use the mailertable feature. This constitutes a database that sendmail can use to base its routing decision upon.

First, you have to create your .mc file. The directory /usr/src/usr.sbin/sendmail/cf/cf is the home of these files. Look around, there are already a few examples. Assuming you have named your file foo.mc, all you need to do in order to convert it into a valid sendmail.cf is: cd /usr/src/usr.sbin/sendmail/cf/cf make foo.cf cp foo.cf /etc/sendmail.cf

A typical .mc file might look like: include(`../m4/cf.m4') VERSIONID(`Your version number') OSTYPE(bsd4.4) FEATURE(nodns) FEATURE(nocanonify) FEATURE(mailertable) define(`UUCP_RELAY', your.uucp.relay) define(`UUCP_MAX_SIZE', 200000) MAILER(local) MAILER(smtp) MAILER(uucp) Cw your.alias.host.name Cw youruucpnodename.UUCP

The nodns and nocanonify features will prevent any usage of the DNS during mail delivery. The UUCP_RELAY clause is needed for bizarre reasons, don't ask. Simply put an Internet hostname there that is able to handle .UUCP pseudo-domain addresses; most likely, you will enter the mail relay of your ISP there.

Once you've got this, you need this file called /etc/mailertable. A typical example of this gender again: # # makemap hash /etc/mailertable.db < /etc/mailertable # horus.interface-business.de uucp-dom:horus .interface-business.de uucp-dom:if-bus interface-business.de uucp-dom:if-bus .heep.sax.de smtp8:%1 horus.UUCP uucp-dom:horus if-bus.UUCP uucp-dom:if-bus . uucp-dom:sax

As you can see, this is part of a real-life file. The first three lines handle special cases where domain-addressed mail should not be sent out to the default route, but instead to some UUCP neighbor in order to ``shortcut'' the delivery path. The next line handles mail to the local Ethernet domain that can be delivered using SMTP. Finally, the UUCP neighbors are mentioned in the .UUCP pseudo-domain notation, to allow for a ``uucp-neighbor!recipient'' override of the default rules. The last line is always a single dot, matching everything else, with UUCP delivery to a UUCP neighbor that serves as your universal mail gateway to the world. All of the node names behind the uucp-dom: keyword must be valid UUCP neighbors, as you can verify using the command uuname.

As a reminder that this file needs to be converted into a DBM database file before being usable, the command line to accomplish this is best placed as a comment at the top of the mailertable. You always have to execute this command each time you change your mailertable.

Final hint: if you are uncertain whether some particular mail routing would work, remember the -bt option to sendmail. It starts sendmail in address test mode; simply enter ``0 '', followed by the address you wish to test for the mail routing. The last line tells you the used internal mail agent, the destination host this agent will be called with, and the (possibly translated) address. Leave this mode by typing Control-D. j@uriah 191% sendmail -bt ADDRESS TEST MODE (ruleset 3 NOT automatically invoked) Enter

> 0 foo@interface-business.de rewrite: ruleset 0 input: foo @ interface-business . de ... rewrite: ruleset 0 returns: $# uucp-dom $@ if-bus $: foo \ < @ interface-business . de > > ^D j@uriah 192% How do I set up mail with a dialup connection to the 'net?

If you've got a statically assigned IP number, you should not need to adjust anything from the default. Set your host name up as your assigned internet name and sendmail will do the rest.

If you've got a dynamically assigned IP number and use a dialup In order to retrieve mail from your mailbox, you'll need to install a retrieval agent. /etc/ppp/ppp.linkup: MYADDR: !bg su user -c fetchmail

I'm assuming that you have an account for poll myISP.com protocol pop3 fetchall pass MySecret;

Needless to say, this file should not be readable by anyone except In order to send mail with the correct The following VERSIONID(`bsd.home.mc version 1.0') OSTYPE(bsd4.4)dnl FEATURE(nouucp)dnl MAILER(local)dnl MAILER(smtp)dnl Cwlocalhost Cwbsd.home MASQUERADE_AS(`myISP.com')dnl FEATURE(allmasquerade)dnl FEATURE(masquerade_envelope)dnl FEATURE(nocanonify)dnl FEATURE(nodns)dnl define(SMART_HOST, `relay.myISP.com') Dmbsd.home define(`confDOMAIN_NAME',`bsd.home')dnl define(`confDELIVERY_MODE',`deferred')dnl

Refer to the previous section for details of how to turn this Eek! I forgot the root password!

Don't Panic! Simply restart the system, type -s at the Boot: prompt to enter Single User mode. At the question about the shell to use, hit ENTER. You'll be dropped to a # prompt. Enter mount -u / to remount your root filesystem read/write, then run How do I keep Control-Alt-Delete from rebooting the system?

Edit the keymap you are using for the console and replace the /usr/share/syscons/keymaps/us.iso.kbd. You may have to instruct /etc/rc.conf to load this keymap explicitly for the change to take effect. Of course if you are using an alternate keymap for your country, you should edit that one instead. diff --git a/FAQ/applications.sgml b/FAQ/applications.sgml index 698d4b698f..02558147d3 100644 --- a/FAQ/applications.sgml +++ b/FAQ/applications.sgml @@ -1,142 +1,142 @@ - + User Applications So, where are all the user applications? -

Please take a look at Please take a look at for info on software packages ported to FreeBSD. The list currently tops 1000 and is growing daily, so come back to check often or subscribe to the for periodic updates on new entries.

Most ports should be available for both the 2.2 and 3.0 branches, and many of them should work on 2.1.x systems as well. Each time a FreeBSD release is made, a snapshot of the ports tree at the time of release in also included in the ports/ directory.

We also support the concept of a ``package'', essentially no more than a gzipped binary distribution with a little extra intelligence embedded in it for doing whatever custom installation work is required. A package can be installed and uninstalled again easily without having to know the gory details of which files it includes.

Use the package installation menu in /stand/sysinstall (under the post-configuration menu item) or invoke the pkg_add(1) command on the specific package files you're interested in installing. Package files can usually be identified by their .tgz suffix and CDROM distribution people will have a packages/All directory on their CD which contains such files. They can also be downloaded over the net for various versions of FreeBSD at the following locations: for 2.1.x-release for 2.2.6-release/2.2-stable for 3.0-current

or your nearest local mirror site.

Note that all ports may not be available as packages since new ones are constantly being added. It is always a good idea to check back periodically to see which packages are available at the master site. Where do I find libc.so.3.0?

You are trying to run a package for 2.2/3.0 on a 2.1.x system. Please take a look at the previous section and get the correct port/package for your system. ghostscript gives lots of errors with my 386/486SX.

You don't have a math co-processor, right? You will need to add the alternative math emulator to your kernel; you do this by adding the following to your kernel config file and it will be compiled in. options GPL_MATH_EMULATE

When I run a SCO/iBCS2 application, it bombs on

You first need to edit the /etc/sysconfig (or ) file in the last section to change the following variable to # Set to YES if you want ibcs2 (SCO) emulation loaded at startup ibcs2=NO

It will load the kernel module at startup.

You'll then need to set up /compat/ibcs2/dev to look like: lrwxr-xr-x 1 root wheel 9 Oct 15 22:20 X0R@ -> /dev/null lrwxr-xr-x 1 root wheel 7 Oct 15 22:20 nfsd@ -> socksys -rw-rw-r-- 1 root wheel 0 Oct 28 12:02 null lrwxr-xr-x 1 root wheel 9 Oct 15 22:20 socksys@ -> /dev/null crw-rw-rw- 1 root wheel 41, 1 Oct 15 22:14 spx

You just need socksys to go to to fake the open & close. The code in -current will handle the rest. This is much cleaner than the way it was done before. If you want the How do I configure INN (Internet News) for my machine?

After installing the inn package or port, an excelent place to start is where you'll find the INN FAQ. What version of Microsoft FrontPage should I get?

Use the Port, Luke! A pre-patched version of Apache is available in the ports tree.

diff --git a/en/tutorials/devel/devel.docb b/en/tutorials/devel/devel.docb index 310401db55..be4ef4d0b8 100644 --- a/en/tutorials/devel/devel.docb +++ b/en/tutorials/devel/devel.docb @@ -1,1835 +1,1835 @@ - + A User's Guide to FreeBSD Programming Tools James Raynard
jraynard@freebsd.org
August 17, 1997 1997 James Raynard This document is an introduction to using some of the programming tools supplied with FreeBSD, although much of it will be applicable to many other versions of Unix. It does not attempt to describe coding in any detail. Most of the document assumes little or no previous programming knowledge, although it is hoped that most programmers will find something of value in it
Introduction<anchor id=foo> FreeBSD offers an excellent development environment. Compilers for C, C++, and Fortran and an assembler come with the basic system, not to mention a Perl interpreter and classic Unix tools such as sed and awk. If that is not enough, there are many more compilers and interpreters in the Ports collection. FreeBSD is very compatible with standards such as POSIX and ANSI C, as well with its own BSD heritage, so it is possible to write applications that will compile and run with little or no modification on a wide range of platforms. However, all this power can be rather overwhelming at first if you've never written programs on a Unix platform before. This document aims to help you get up and running, without getting too deeply into more advanced topics. The intention is that this document should give you enough of the basics to be able to make some sense of the documentation. Most of the document requires little or no knowledge of programming, although it does assume a basic competence with using Unix and a willingness to learn! Introduction to Programming A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to perform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can give these instructions, or commands as they are usually called. One way uses an interpreter, the other a compiler. As human languages are too difficult for a computer to understand in an unambiguous way, commands are usually written in one or other languages specially designed for the purpose. Interpreters With an interpreter, the language comes as an environment, where you type in commands at a prompt and the environment executes them for you. For more complicated programs, you can type the commands into a file and get the interpreter to load the file and execute the commands in it. If anything goes wrong, many interpreters will drop you into a debugger to help you track down the problem. The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected readily. The biggest disadvantage comes when you want to share your programs with someone. They must have the same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. Also users may not appreciate being thrown into a debugger if they press the wrong key! From a performance point of view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers. In my opinion, interpreted languages are the best way to start if you have not done any programming before. This kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also be argued that the Unix shell (sh, csh) is itself an interpreter, and many people do in fact write shell scripts to help with various housekeeping tasks on their machine. Indeed, part of the original Unix philosophy was to provide lots of small utility programs that could be linked together in shell scripts to perform useful tasks. Interpreters available with FreeBSD Here is a list of interpreters that are available as FreeBSD packages, with a brief discussion of some of the more popular interpreted languages. To get one of these packages, all you need to do is to click on the hotlink for the package, then run $ pkg_add package name as root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later system for the package to work! BASIC Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching University students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been the first programming language for many programmers. It's also the foundation for Visual Basic. The Bywater Basic Interpreter and the Phil Cockroft's Basic Interpreter (formerly Rabbit Basic) are available as FreeBSD FreeBSD packages Lisp A language that was developed in the late 1950s as an alternative to the number-crunching languages that were popular at the time. Instead of being based on numbers, Lisp is based on lists; in fact the name is short for List Processing. Very popular in AI (Artificial Intelligence) circles. Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. FreeBSD has GNU Common Lisp available as a package. Perl Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. Version 4, which is probably still the most widely-used version, comes with FreeBSD; the newer Perl Version 5 is available as a package. Scheme A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it is simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to be used in research work. FreeBSD has packages of the Elk Scheme Interpreter, the MIT Scheme Interpreter and the SCM Scheme Interpreter. Icon The Icon Programming Language. Logo Brian Harvey's LOGO Interpreter. Python The Python Object-Oriented Programming Language Compilers Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then run the compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the editor; if it did compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works properly.If you run it in the shell, you may get a core dump. Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things which are very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating system—or even writing your own operating system! It's also useful if you need to write very efficient code, as the compiler can take its time and optimise the code, which would not be acceptable in an interpreter. And distributing a program written for a compiler is usually more straightforward than one written for an interpreter—you can just give them a copy of the executable, assuming they have the same operating system as you. Compiled languages include Pascal, C and C++. C and C++ are rather unforgiving languages, and best suited to more experienced programmers; Pascal, on the other hand, was designed as an educational language, and is quite a good language to start with. Unfortunately, FreeBSD doesn't have any Pascal support, except for a Pascal-to-C converter in the ports. As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not have an IDE as such; however it is possible to use Emacs for this purpose. This is discussed in . Compiling with <command>cc</command> This section deals only with the GNU compiler for C and C++, since that comes with the base FreeBSD system. It can be invoked by either cc or gcc. The details of producing a program with an interpreter vary considerably between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. Once you've written your masterpiece, the next step is to convert it into something that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which is done by a separate program. Pre-process your source code to remove comments and do other tricks like expanding macros in C. Check the syntax of your code to see if you have obeyed the rules of the language. If you have not, it will complain! Convert the source code into assembly language—this is very close to machine code, but still understandable by humans. Allegedly.To be strictly accurate, cc converts the source code into its own, machine-independent p-code instead of assembly language at this stage. Convert the assembly language into machine code—yep, we are talking bits and bytes, ones and zeros here. Check that you have used things like functions and global variables in a consistent way. For example, if you have called a non-existent function, it will complain. If you are trying to produce an executable from several source code files, work out how to fit them all together. Work out how to produce something that the system's run-time loader will be able to load into memory and run. Finally, write the executable on the file system. The word compiling is often used to refer to just steps 1 to 4—the others are referred to as linking. Sometimes step 1 is referred to as pre-processing and steps 3-4 as assembling. Fortunately, almost all this detail is hidden from you, as cc is a front end that manages calling all these programs with the right arguments for you; simply typing $ cc foobar.c will cause foobar.c to be compiled by all the steps above. If you have more than one file to compile, just do something like $ cc foo.c bar.c Note that the syntax checking is just that—checking the syntax. It will not check for any logical mistakes you may have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort.In case you didn't know, a binary sort is an efficient way of sorting things into order and a bubble sort isn't. There are lots and lots of options for cc, which are all in the man page. Here are a few of the most important ones, with examples of how to use them. The output name of the file. If you do not use this option, cc will produce an executable called a.out.The reasons for this are buried in the mists of history. $ cc foobar.c executable is a.out $ cc -o foobar foobar.c executable is foobar Just compile the file, do not link it. Useful for toy programs where you just want to check the syntax, or if you are using a Makefile. $ cc -c foobar.c This will produce an object file (not an executable) called foobar.o. This can be linked together with other object files into an executable. Create a debug version of the executable. This makes the compiler put information into the executable about which line of which source file corresponds to which function call. A debugger can use this information to show the source code as you step through the program, which is very useful; the disadvantage is that all this extra information makes the program much bigger. Normally, you compile with while you are developing a program and then compile a release version without when you're satisfied it works properly. $ cc -g foobar.c This will produce a debug version of the program.Note, we didn't use the flag to specify the executable name, so we will get an executable called a.out. Producing a debug version called foobar is left as an exercise for the reader! Create an optimised version of the executable. The compiler performs various clever tricks to try and produce an executable that runs faster than normal. You can add a number after the to specify a higher level of optimisation, but this often exposes bugs in the compiler's optimiser. For instance, the version of cc that comes with the 2.1.0 release of FreeBSD is known to produce bad code with the option in some circumstances. Optimisation is usually only turned on when compiling a release version. $ cc -O -o foobar foobar.c This will produce an optimised version of foobar. The following three flags will force cc to check that your code complies to the relevant international standard, often referred to as the ANSI standard, though strictly speaking it is an ISO standard. Enable all the warnings which the authors of cc believe are worthwhile. Despite the name, it will not enable all the warnings cc is capable of. Turn off most, but not all, of the non-ANSI C features provided by cc. Despite the name, it does not guarantee strictly that your code will comply to the standard. Turn off all cc's non-ANSI C features. Without these flags, cc will allow you to use some of its non-standard extensions to the standard. Some of these are very useful, but will not work with other compilers—in fact, one of the main aims of the standard is to allow people to write code that will work with any compiler on any system. This is known as portable code. Generally, you should try to make your code as portable as possible, as otherwise you may have to completely re-write the program later to get it to work somewhere else—and who knows what you may be using in a few years time? $ cc -Wall -ansi -pedantic -o foobar foobar.c This will produce an executable foobar after checking foobar.c for standard compliance. Specify a function library to be used during when linking. The most common example of this is when compiling a program that uses some of the mathematical functions in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell the compiler to add it. The rule is that if the library is called libsomething.a, you give cc the argument . For example, the math library is libm.a, so you give cc the argument . A common gotcha with the math library is that it has to be the last library on the command line. $ cc -o foobar foobar.c -lm This will link the math library functions into foobar. If you are compiling C++ code, you need to add , or if you are using FreeBSD 2.2 or later, to the command line argument to link the C++ library functions. Alternatively, you can run c++ instead of cc, which does this for you. c++ can also be invoked as g++ on FreeBSD. $ cc -o foobar foobar.cc -lg++ For FreeBSD 2.1.6 and earlier $ cc -o foobar foobar.cc -lstdc++ For FreeBSD 2.2 and later $ c++ -o foobar foobar.cc Each of these will both produce an executable foobar from the C++ source file foobar.cc. Note that, on Unix systems, C++ source files traditionally end in .C, .cxx or .cc, rather than the MS-DOS style .cpp (which was already used for something else). gcc used to rely on this to work out what kind of compiler to use on the source file; however, this restriction no longer applies, so you may now call your C++ files .cpp with impunity! Common <command>cc</command> Queries and Problems Q. I am trying to write a program which uses the sin() function and I get an error like this. What does it mean? /var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment A. When using mathematical functions like sin(), you have to tell cc to link in the math library, like so: $ cc -o foobar foobar.c -lm Q. All right, I wrote this simple program to practice using . All it does is raise 2.1 to the power of 6. #include <stdio.h> int main() { float f; f = pow(2.1, 6); printf("2.1 ^ 6 = %f\n", f); return 0; } and I compiled it as: $ cc temp.c -lm like you said I should, but I get this when I run it: $ ./a.out 2.1 ^ 6 = 1023.000000 This is not the right answer! What is going on? A. When the compiler sees you call a function, it checks if it has already seen a prototype for it. If it has not, it assumes the function returns an int, which is definitely not what you want here. Q. So how do I fix this? A. The prototypes for the mathematical functions are in math.h. If you include this file, the compiler will be able to find the prototype and it will stop doing strange things to your calculation! #include <math.h> #include <stdio.h> int main() { ... After recompiling it as you did before, run it: $ ./a.out 2.1 ^ 6 = 85.766121 If you are using any of the mathematical functions, always include math.h and remember to link in the math library. Q. I compiled a file called foobar.c and I cannot find an executable called foobar. Where's it gone? A. Remember, cc will call the executable a.out unless you tell it differently. Use the option: $ cc -o foobar foobar.c Q. OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it? A. Unlike MS-DOS, Unix does not look in the current directory when it is trying to find out which executable you want it to run, unless you tell it to. Either type ./foobar, which means run the file called foobar in the current directory, or change your PATH environment variable so that it looks something like bin:/usr/bin:/usr/local/bin:. The dot at the end means look in the current directory if it is not in any of the others. Q. I called my executable test, but nothing happens when I run it. What is going on? A. Most Unix systems have a program called test in /usr/bin and the shell is picking that one up before it gets to checking the current directory. Either type: $ ./test or choose a better name for your program! Q. I compiled my program and it seemed to run all right at first, then there was an error and it said something about core dumped. What does that mean? A. The name core dump dates back to the very early days of Unix, when the machines used core memory for storing data. Basically, if the program failed under certain conditions, the system would write the contents of core memory to disk in a file called core, which the programmer could then pore over to find out what went wrong. Q. Fascinating stuff, but what I am supposed to do now? A. Use gdb to analyse the core (see ). Q. When my program dumped core, it said something about a segmentation fault. What's that? A. This basically means that your program tried to perform some sort of illegal operation on memory; Unix is designed to protect the operating system and other programs from rogue programs. Common causes for this are: Trying to write to a NULL pointer, eg char *foo = NULL; strcpy(foo, "bang!"); Using a pointer that hasn't been initialised, eg char *foo; strcpy(foo, "bang!"); The pointer will have some random value that, with luck, will point into an area of memory that isn't available to your program and the kernel will kill your program before it can do any damage. If you're unlucky, it'll point somewhere inside your own program and corrupt one of your data structures, causing the program to fail mysteriously. Trying to access past the end of an array, eg int bar[20]; bar[27] = 6; Trying to store something in read-only memory, eg char *foo = "My string"; strcpy(foo, "bang!"); Unix compilers often put string literals like "My string" into read-only areas of memory. Doing naughty things with malloc() and free(), eg char bar[80]; free(bar); or char *foo = malloc(27); free(foo); free(foo); Making one of these mistakes will not always lead to an error, but they are always bad practice. Some systems and compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try them on an another. Q. Sometimes when I get a core dump it says bus error. It says in my Unix book that this means a hardware problem, but the computer still seems to be working. Is this true? A. No, fortunately not (unless of course you really do have a hardware problem…). This is usually another way of saying that you accessed memory in a way you shouldn't have. Q. This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. Can I do this, or do I have to wait until there's an error? A. Yes, just go to another console or xterm, do $ ps to find out the process ID of your program, and do $ kill -ABRT pid where pid is the process ID you looked up. This is useful if your program has got stuck in an infinite loop, for instance. If your program happens to trap SIGABRT, there are several other signals which have a similar effect. Make What is <command>make</command>? When you're working on a simple program with only one or two source files, typing in $ cc file1.c file2.c is not too bad, but it quickly becomes very tedious when there are several files—and it can take a while to compile, too. One way to get around this is to use object files and only recompile the source file if the source code has changed. So we could have something like: $ cc file1.o file2.ofile37.c &hellip if we'd changed file37.c, but not any of the others, since the last time we compiled. This may speed up the compilation quite a bit, but doesn't solve the typing problem. Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it very inefficient on a large project. What happens if we have hundreds of source files lying about? What if we're working in a team with other people who forget to tell us when they've changed one of their source files that we use? Perhaps we could put the two solutions together and write something like a shell script that would contain some kind of magic rule saying when a source file needs compiling. Now all we need now is a program that can understand these rules, as it's a bit too complicated for the shell. This program is called make. It reads in a file, called a makefile, that tells it how different files depend on each other, and works out which files need to be re-compiled and which ones don't. For example, a rule could say something like if fromboz.o is older than fromboz.c, that means someone must have changed fromboz.c, so it needs to be re-compiled. The makefile also has rules telling make how to re-compile the source file, making it a much more powerful tool. Makefiles are typically kept in the same directory as the source they apply to, and can be called makefile, Makefile or MAKEFILE. Most programmers use the name Makefile, as this puts it near the top of a directory listing, where it can easily be seen.They don't use the MAKEFILE form as block capitals are often used for documentation files like README. Example of using <command>make</command> Here's a very simple make file: foo: foo.c cc -o foo foo.c It consists of two lines, a dependency line and a creation line. The dependency line here consists of the name of the program (known as the target), followed by a colon, then whitespace, then the name of the source file. When make reads this line, it looks to see if foo exists; if it exists, it compares the time foo was last modified to the time foo.c was last modified. If foo does not exist, or is older than foo.c, it then looks at the creation line to find out what to do. In other words, this is the rule for working out when foo.c needs to be re-compiled. The creation line starts with a tab (press the tab key) and then the command you would type to create foo if you were doing it at a command prompt. If foo is out of date, or does not exist, make then executes this command to create it. In other words, this is the rule which tells make how to re-compile foo.c. So, when you type make, it will make sure that foo is up to date with respect to your latest changes to foo.c. This principle can be extended to Makefiles with hundreds of targets—in fact, on FreeBSD, it is possible to compile the entire operating system just by typing make world in the appropriate directory! Another useful property of makefiles is that the targets don't have to be programs. For instance, we could have a make file that looks like this: foo: foo.c cc -o foo foo.c install: cp foo /home/me We can tell make which target we want to make by typing: $ make target make will then only look at that target and ignore any others. For example, if we type make foo with the makefile above, make will ignore the install target. If we just type make on its own, make will always look at the first target and then stop without looking at any others. So if we typed make here, it will just go to the foo target, re-compile foo if necessary, and then stop without going on to the install target. Notice that the install target doesn't actually depend on anything! This means that the command on the following line is always executed when we try to make that target by typing make install. In this case, it will copy foo into the user's home directory. This is often used by application makefiles, so that the application can be installed in the correct directory when it has been correctly compiled. This is a slightly confusing subject to try and explain. If you don't quite understand how make works, the best thing to do is to write a simple program like hello world and a make file like the one above and experiment. Then progress to using more than one source file, or having the source file include a header file. The touch command is very useful here—it changes the date on a file without you having to edit it. FreeBSD Makefiles Makefiles can be rather complicated to write. Fortunately, BSD-based systems like FreeBSD come with some very powerful ones as part of the system. One very good example of this is the FreeBSD ports system. Here's the essential part of a typical ports Makefile: MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include <bsd.port.mk> Now, if we go to the directory for this port and type make, the following happens: A check is made to see if the source code for this port is already on the system. If it isn't, an FTP connection to the URL in MASTER_SITES is set up to download the source. The checksum for the source is calculated and compared it with one for a known, good, copy of the source. This is to make sure that the source was not corrupted while in transit. Any changes required to make the source work on FreeBSD are applied—this is known as patching. Any special configuration needed for the source is done. (Many Unix program distributions try to work out which version of Unix they are being compiled on and which optional Unix features are present—this is where they are given the information in the FreeBSD ports scenario). The source code for the program is compiled. In effect, we change to the directory where the source was unpacked and do make—the program's own make file has the necessary information to build the program. We now have a compiled version of the program. If we wish, we can test it now; when we feel confident about the program, we can type make install. This will cause the program and any supporting files it needs to be copied into the correct location; an entry is also made into a package database, so that the port can easily be uninstalled later if we change our mind about it. Now I think you'll agree that's rather impressive for a four line script! The secret lies in the last line, which tells make to look in the system makefile called bsd.port.mk. It's easy to overlook this line, but this is where all the clever stuff comes from—someone has written a makefile that tells make to do all the things above (plus a couple of other things I didn't mention, including handling any errors that may occur) and anyone can get access to that just by putting a single line in their own make file! If you want to have a look at these system makefiles, they're in /usr/share/mk, but it's probably best to wait until you've had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) More advanced uses of <command>make</command> Make is a very powerful tool, and can do much more than the simple example above shows. Unfortunately, there are several different versions of make, and they all differ considerably. The best way to learn what they can do is probably to read the documentation—hopefully this introduction will have given you a base from which you can do this. The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in /usr/share/doc/psd/12.make. To view it, do $ zmore paper.ascii.gz in that directory. Many applications in the ports use GNU make, which has a very good set of info pages. If you have installed any of these ports, GNU make will automatically have been installed as gmake. It's also available as a port and package in its own right. To view the info pages for GNU make, you will have to edit the dir file in the /usr/local/info directory to add an entry for it. This involves adding a line like * Make: (make). The GNU Make utility. to the file. Once you have done this, you can type info and then select make from the menu (or in Emacs, do C-h i). Debugging The Debugger The debugger that comes with FreeBSD is called gdb (GNU debugger). You start it up by typing $ gdb progname although most people prefer to run it inside Emacs. You can do this by: M-x gdb RET progname RET Using a debugger allows you to run the program under more controlled circumstances. Typically, you can step through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a certain point and then stop, and so on. You can even attach to a program that's already running, or load a core file to investigate why the program crashed. It's even possible to debug the kernel, though that's a little trickier than the user applications we'll be discussing in this section. gdb has quite good on-line help, as well as a set of info pages, so this section will concentrate on a few of the basic commands. Finally, if you find its text-based command-prompt style off-putting, there's a graphical front-end for it xxgdb +URL="../../ports/devel.html">xxgdb in the ports collection. This section is intended to be an introduction to using gdb and does not cover specialised topics such as debugging the kernel. Running a program in the debugger You'll need to have compiled the program with the option to get the most out of using gdb. It will work without, but you'll only see the name of the function you're in, instead of the source code. If you see a line like: … (no debugging symbols found) …when gdb starts up, you'll know that the program wasn't compiled with the option. At the gdb prompt, type break main. This will tell the debugger to skip over the preliminary set-up code in the program and start at the beginning of your code. Now type run to start the program—it will start at the beginning of the set-up code and then get stopped by the debugger when it calls main(). (If you've ever wondered where main() gets called from, now you know!). You can now step through the program, a line at a time, by pressing n. If you get to a function call, you can step into it by pressing s. Once you're in a function call, you can return from stepping into a function call by pressing f. You can also use up and down to take a quick look at the caller. Here's a simple example of how to spot a mistake in a program with gdb. This is our program (with a deliberate mistake): #include <stdio.h> int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } This program sets i to be 5 and passes it to a function bazz() which prints out the number we gave it. When we compile and run the program we get $ cc -g -o temp temp.c $ ./temp This is my program anint = 4231 That wasn't what we expected! Time to see what's going on!$ gdb temp GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) break main Skip the set-up code Breakpoint 1 at 0x160f: file temp.c, line 9. gdb puts breakpoint at main() (gdb) run Run as far as main() Starting program: /home/james/tmp/temp Program starts running Breakpoint 1, main () at temp.c:9 gdb stops at main() (gdb) n Go to next line This is my program Program prints out (gdb) s step into bazz() bazz (anint=4231) at temp.c:17 gdb displays stack frame (gdb) Hang on a minute! How did anint get to be 4231? Didn't we set it to be 5 in main()? Let's move up to main() and have a look. (gdb) up Move up call stack #1 0x1625 in main () at temp.c:11 gdb displays stack frame (gdb) p i Show us the value of i $1 = 4231 gdb displays 4231 Oh dear! Looking at the code, we forgot to initialise i. We meant to put … main() { int i; i = 5; printf("This is my program\n"); &hellip but we left the i=5; line out. As we didn't initialise i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be 4231. gdb displays the stack frame every time we go into or out of a function, even if we're using up and down to move around the call stack. This shows the name of the function and the values of its arguments, which helps us keep track of where we are and what's going on. (The stack is a storage area where the program stores information about the arguments passed to functions and where to go when it returns from a function call). Examining a core file A core file is basically a file which contains the complete state of the process when it crashed. In the good old days, programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called progname.core instead of just core, to make it clearer which program a core file belongs to. To examine a core file, start up gdb in the usual way. Instead of typing break or run, type (gdb) core progname.core If you're not in the same directory as the core file, you'll have to do dir /path/to/core/file first. You should see something like this: $ gdb a.out GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) core a.out.core Core was generated by `a.out'. Program terminated with signal 11, Segmentation fault. Cannot access memory at address 0x7020796d. #0 0x164a in bazz (anint=0x5) at temp.c:17 (gdb) In this case, the program was called a.out, so the core file is called a.out.core. We can see that the program crashed due to trying to access an area in memory that was not available to it in a function called bazz. Sometimes it's useful to be able to see how a function was called, as the problem could have occurred a long way up the call stack in a complex program. The bt command causes gdb to print out a back-trace of the call stack: (gdb) bt #0 0x164a in bazz (anint=0x5) at temp.c:17 #1 0xefbfd888 in end () #2 0x162c in main () at temp.c:11 (gdb)The end() function is called when a program crashes; in this case, the bazz() function was called from main(). Attaching to a running program One of the neatest features about gdb is that it can attach to a program that's already running. Of course, that assumes you have sufficient permissions to do so. A common problem is when you are stepping through a program that forks, and you want to trace the child, but the debugger will only let you trace the parent. What you do is start up another gdb, use ps to find the process ID for the child, and do(gdb) attach pid in gdb, and then debug as usual. That's all very well, you're probably thinking, but by the time I've done that, the child process will be over the hill and far away. Fear not, gentle reader, here's how to do it (courtesy of the gdb info pages): &hellip if ((pid = fork()) < 0) /* _Always_ check this */ error(); else if (pid == 0) { /* child */ int PauseMode = 1; while (PauseMode) sleep(10); /* Wait until someone attaches to us */ &hellip } else { /* parent */ &hellip Now all you have to do is attach to the child, set PauseMode to 0, and wait for the sleep() call to return! Using Emacs as a Development Environment Emacs Unfortunately, Unix systems don't come with the kind of everything-you-ever-wanted-and-lots-more-you-didn't-in-one-gigantic-package integrated development environments that other systems have.At least, not unless you pay out very large sums of money. However, it is possible to set up your own environment. It may not be as pretty, and it may not be quite as integrated, but you can set it up the way you want it. And it's free. And you have the source to it. The key to it all is Emacs. Now there are some people who loathe it, but many who love it. If you're one of the former, I'm afraid this section will hold little of interest to you. Also, you'll need a fair amount of memory to run it—I'd recommend 8MB in text mode and 16MB in X as the bare minimum to get reasonable performance. Emacs is basically a highly customisable editor—indeed, it has been customised to the point where it's more like an operating system than an editor! Many developers and sysadmins do in fact spend practically all their time working inside Emacs, leaving it only to log out. It's impossible even to summarise everything Emacs can do here, but here are some of the features of interest to developers: Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to start/end of block expression, etc, etc. Pull-down menus and online help. Language-dependent syntax highlighting and indentation. Completely customisable. You can compile and debug programs within Emacs. On a compilation error, you can jump to the offending line of source code. Friendly-ish front-end to the info program used for reading GNU hypertext documentation, including the documentation on Emacs itself. Friendly front-end to gdb, allowing you to look at the source code as you step through your program. You can read Usenet news and mail while your program is compiling. And doubtless many more that I've overlooked. Emacs can be installed on FreeBSD using the Emacs +URL="../../ports/editors.html">the Emacs port. Once it's installed, start it up and do C-h t to read an Emacs tutorial—that means hold down the control key, press h, let go of the control key, and then press t. (Alternatively, you can you use the mouse to select Emacs Tutorial from the Help menu). Although Emacs does have menus, it's well worth learning the key bindings, as it's much quicker when you're editing something to press a couple of keys than to try and find the mouse and then click on the right place. And, when you're talking to seasoned Emacs users, you'll find they often casually throw around expressions like M-x replace-s RET foo RET bar RET so it's useful to know what they mean. And in any case, Emacs has far too many useful functions for them to all fit on the menu bars. Fortunately, it's quite easy to pick up the key-bindings, as they're displayed next to the menu item. My advice is to use the menu item for, say, opening a file until you understand how it works and feel confident with it, then try doing C-x C-f. When you're happy with that, move on to another menu command. If you can't remember what a particular combination of keys does, select Describe Key from the Help menu and type it in—Emacs will tell you what it does. You can also use the Command Apropos menu item to find out all the commands which contain a particular word in them, with the key binding next to it. By the way, the expression above means hold down the Meta key, press x, release the Meta key, type replace-s (short for replace-string—another feature of Emacs is that you can abbreviate commands), press the return key, type foo (the string you want replaced), press the return key, type bar (the string you want to replace foo with) and press return again. Emacs will then do the search-and-replace operation you've just requested. If you're wondering what on earth the Meta key is, it's a special key that many Unix workstations have. Unfortunately, PC's don't have one, so it's usually the alt key (or if you're unlucky, the escape key). Oh, and to get out of Emacs, do C-x C-c (that means hold down the control key, press c, press x and release the control key). If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore the bit in the documentation where it says C-z is the usual way to leave Emacs—that leaves Emacs hanging around in the background, and is only really useful if you're on a system which doesn't have virtual terminals). Configuring Emacs Emacs does many wonderful things; some of them are built in, some of them need to be configured. Instead of using a proprietary macro language for configuration, Emacs uses a version of Lisp specially adapted for editors, known as Emacs Lisp. This can be quite useful if you want to go on and learn something like Common Lisp, as it's considerably smaller than Common Lisp (although still quite big!). The best way to learn Emacs Lisp is to download the Emacs Tutorial However, there's no need to actually know any Lisp to get started with configuring Emacs, as I've included a sample .emacs file, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it's already running; it will read the commands from the file and (hopefully) give you a useful basic setup. A sample <filename>.emacs</filename> file Unfortunately, there's far too much here to explain it in detail; however there are one or two points worth mentioning. Everything beginning with a ; is a comment and is ignored by Emacs. In the first line, the -*- Emacs-Lisp -*- is so that we can edit the .emacs file itself within Emacs and get all the fancy features for editing Emacs Lisp. Emacs usually tries to guess this based on the filename, and may not get it right for .emacs. The tab key is bound to an indentation function in some modes, so when you press the tab key, it will indent the current line of code. If you want to put a tab character in whatever you're writing, hold the control key down while you're pressing the tab key. This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by guessing the language from the filename. Emacs already has a pre-defined function called next-error. In a compilation output window, this allows you to move from one compilation error to the next by doing M-n; we define a complementary function, previous-error, that allows you to go to a previous error by doing M-p. The nicest feature of all is that C-c C-c will open up the source file in which the error occurred and jump to the appropriate line. We enable Emacs's ability to act as a server, so that if you're doing something outside Emacs and you want to edit a file, you can just type in $ emacsclient filename and then you can edit the file in your Emacs!Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit a file. A sample <filename>.emacs</filename> file ;; -*-Emacs-Lisp-*- ;; This file is designed to be re-evaled; use the variable first-time ;; to avoid any problems with this. (defvar first-time t "Flag signifying this is the first time that .emacs has been evaled") ;; Meta (global-set-key "\M- " 'set-mark-command) (global-set-key "\M-\C-h" 'backward-kill-word) (global-set-key "\M-\C-r" 'query-replace) (global-set-key "\M-r" 'replace-string) (global-set-key "\M-g" 'goto-line) (global-set-key "\M-h" 'help-command) ;; Function keys (global-set-key [f1] 'manual-entry) (global-set-key [f2] 'info) (global-set-key [f3] 'repeat-complex-command) (global-set-key [f4] 'advertised-undo) (global-set-key [f5] 'eval-current-buffer) (global-set-key [f6] 'buffer-menu) (global-set-key [f7] 'other-window) (global-set-key [f8] 'find-file) (global-set-key [f9] 'save-buffer) (global-set-key [f10] 'next-error) (global-set-key [f11] 'compile) (global-set-key [f12] 'grep) (global-set-key [C-f1] 'compile) (global-set-key [C-f2] 'grep) (global-set-key [C-f3] 'next-error) (global-set-key [C-f4] 'previous-error) (global-set-key [C-f5] 'display-faces) (global-set-key [C-f8] 'dired) (global-set-key [C-f10] 'kill-compilation) ;; Keypad bindings (global-set-key [up] "\C-p") (global-set-key [down] "\C-n") (global-set-key [left] "\C-b") (global-set-key [right] "\C-f") (global-set-key [home] "\C-a") (global-set-key [end] "\C-e") (global-set-key [prior] "\M-v") (global-set-key [next] "\C-v") (global-set-key [C-up] "\M-\C-b") (global-set-key [C-down] "\M-\C-f") (global-set-key [C-left] "\M-b") (global-set-key [C-right] "\M-f") (global-set-key [C-home] "\M-<") (global-set-key [C-end] "\M->") (global-set-key [C-prior] "\M-<") (global-set-key [C-next] "\M->") ;; Mouse (global-set-key [mouse-3] 'imenu) ;; Misc (global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab. (setq backup-by-copying-when-mismatch t) ;; Treat 'y' or <CR> as yes, 'n' as no. (fset 'yes-or-no-p 'y-or-n-p) (define-key query-replace-map [return] 'act) (define-key query-replace-map [?\C-m] 'act) ;; Load packages (require 'desktop) (require 'tar-mode) ;; Pretty diff mode (autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files-remote "ediff" "Intelligent Emacs interface to diff") (if first-time (setq auto-mode-alist (append '(("\\.cpp$" . c++-mode) ("\\.hpp$" . c++-mode) ("\\.lsp$" . lisp-mode) ("\\.scm$" . scheme-mode) ("\\.pl$" . perl-mode) ) auto-mode-alist))) ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") (defvar font-lock-mode-keyword-alist '((c++-c-mode . c-font-lock-keywords) (perl-mode . perl-font-lock-keywords)) "Associations between modes and keywords") (defun font-lock-auto-mode-select () "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list" (if (memq major-mode font-lock-auto-mode-list) (progn (font-lock-mode t)) ) ) (global-set-key [M-f1] 'font-lock-fontify-buffer) ;; New dabbrev stuff ;(require 'new-dabbrev) (setq dabbrev-always-check-other-buffers t) (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") (add-hook 'emacs-lisp-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'c-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'text-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) t) (set (make-local-variable 'dabbrev-case-replace) t))) ;; C++ and C mode... (defun my-c++-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c++-mode-map "\C-ce" 'c-comment-edit) (setq c++-auto-hungry-initial-state 'none) (setq c++-delete-function 'backward-delete-char) (setq c++-tab-always-indent t) (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c++-empty-arglist-indent 4)) (defun my-c-mode-hook () (setq tab-width 4) (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c-mode-map "\C-ce" 'c-comment-edit) (setq c-auto-hungry-initial-state 'none) (setq c-delete-function 'backward-delete-char) (setq c-tab-always-indent t) ;; BSD-ish indentation style (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c-brace-offset -4) (setq c-argdecl-indent 0) (setq c-label-offset -4)) ;; Perl mode (defun my-perl-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (setq perl-indent-level 4) (setq perl-continued-statement-offset 4)) ;; Scheme mode... (defun my-scheme-mode-hook () (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent)) ;; Emacs-Lisp mode... (defun my-lisp-mode-hook () (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key lisp-mode-map "\C-i" 'lisp-indent-line) (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp)) ;; Add all of the hooks... (add-hook 'c++-mode-hook 'my-c++-mode-hook) (add-hook 'c-mode-hook 'my-c-mode-hook) (add-hook 'scheme-mode-hook 'my-scheme-mode-hook) (add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'perl-mode-hook 'my-perl-mode-hook) ;; Complement to next-error (defun previous-error (n) "Visit previous compilation error message and corresponding source code." (interactive "p") (next-error (- n))) ;; Misc... (transient-mark-mode 1) (setq mark-even-if-inactive t) (setq visible-bell nil) (setq next-line-add-newlines nil) (setq compile-command "make") (setq suggest-key-bindings nil) (put 'eval-expression 'disabled nil) (put 'narrow-to-region 'disabled nil) (put 'set-goal-column 'disabled nil) ;; Elisp archive searching (autoload 'format-lisp-code-directory "lispdir" nil t) (autoload 'lisp-dir-apropos "lispdir" nil t) (autoload 'lisp-dir-retrieve "lispdir" nil t) (autoload 'lisp-dir-verify "lispdir" nil t) ;; Font lock mode (defun my-make-face (face colour &optional bold) "Create a face from a colour and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face colour) (if bold (make-face-bold face)) ) (if (eq window-system 'x) (progn (my-make-face 'blue "blue") (my-make-face 'red "red") (my-make-face 'green "dark green") (setq font-lock-comment-face 'blue) (setq font-lock-string-face 'bold) (setq font-lock-type-face 'bold) (setq font-lock-keyword-face 'bold) (setq font-lock-function-name-face 'red) (setq font-lock-doc-string-face 'green) (add-hook 'find-file-hooks 'font-lock-auto-mode-select) (setq baud-rate 1000000) (global-set-key "\C-cmm" 'menu-bar-mode) (global-set-key "\C-cms" 'scroll-bar-mode) (global-set-key [backspace] 'backward-delete-char) ; (global-set-key [delete] 'delete-char) (standard-display-european t) (load-library "iso-transl"))) ;; X11 or PC using direct screen writes (if window-system (progn ;; (global-set-key [M-f1] 'hilit-repaint-command) ;; (global-set-key [M-f2] [?\C-u M-f1]) (setq hilit-mode-enable-list '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode scheme-mode) hilit-auto-highlight nil hilit-auto-rehighlight 'visible hilit-inhibit-hooks nil hilit-inhibit-rebinding t) (require 'hilit19) (require 'paren)) (setq baud-rate 2400) ; For slow serial connections ) ;; TTY type terminal (if (and (not window-system) (not (equal system-type 'ms-dos))) (progn (if first-time (progn (keyboard-translate ?\C-h ?\C-?) (keyboard-translate ?\C-? ?\C-h))))) ;; Under UNIX (if (not (equal system-type 'ms-dos)) (progn (if first-time (server-start)))) ;; Add any face changes here (add-hook 'term-setup-hook 'my-term-setup-hook) (defun my-term-setup-hook () (if (eq window-system 'pc) (progn ;; (set-face-background 'default "red") ))) ;; Restore the "desktop" - do this as late as possible (if first-time (progn (desktop-load-default) (desktop-read))) ;; Indicate that this file has been read at least once (setq first-time nil) ;; No need to debug anything now (setq debug-on-error nil) ;; All done (message "All done, %s%s" (user-login-name) ".") Extending the Range of Languages Emacs Understands Now, this is all very well if you only want to program in the languages already catered for in the .emacs file (C, C++, Perl, Lisp and Scheme), but what happens if a new language called whizbang comes out, full of exciting features? The first thing to do is find out if whizbang comes with any files that tell Emacs about the language. These usually end in .el, short for Emacs Lisp. For example, if whizbang is a FreeBSD port, we can locate these files by doing $ find /usr/ports/lang/whizbang -name "*.el" -print and install them by copying them into the Emacs site Lisp directory. On FreeBSD 2.1.0-RELEASE, this is /usr/local/share/emacs/site-lisp. So for example, if the output from the find command was /usr/ports/lang/whizbang/work/misc/whizbang.el we would do $ cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp Next, we need to decide what extension whizbang source files have. Let's say for the sake of argument that they all end in .wiz. We need to add an entry to our .emacs file to make sure Emacs will be able to use the information in whizbang.el. Find the auto-mode-alist entry in .emacs and add a line for whizbang, such as: … ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) This means that Emacs will automatically go into whizbang-mode when you edit a file ending in .wiz. Just below this, you'll find the font-lock-auto-mode-list entry. Add whizbang-mode to it like so: ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") This means that Emacs will always enable font-lock-mode (ie syntax highlighting) when editing a .wiz file. And that's all that's needed. If there's anything else you want done automatically when you open up a .wiz file, you can add a whizbang-mode hook (see my-scheme-mode-hook for a simple example that adds auto-indent). Further Reading Brian Harvey and Matthew Wright Simply Scheme MIT 1994. ISBN 0-262-08226-8 Randall Schwartz Learning Perl O'Reilly 1993 ISBN 1-56592-042-2 Patrick Henry Winston and Berthold Klaus Paul Horn Lisp (3rd Edition) Addison-Wesley 1989 ISBN 0-201-08319-1 Brian W. Kernighan and Rob Pike The Unix Programming Environment Prentice-Hall 1984 ISBN 0-13-937681-X Brian W. Kernighan and Dennis M. Ritchie The C Programming Language (2nd Edition) Prentice-Hall 1988 ISBN 0-13-110362-8 Bjarne Stroustrup The C++ Programming Language Addison-Wesley 1991 ISBN 0-201-53992-6 W. Richard Stevens Advanced Programming in the Unix Environment Addison-Wesley 1992 ISBN 0-201-56317-7 W. Richard Stevens Unix Network Programming Prentice-Hall 1990 ISBN 0-13-949876-1
diff --git a/en/tutorials/newuser/newuser.docb b/en/tutorials/newuser/newuser.docb index 9adefd509b..c8ab990405 100644 --- a/en/tutorials/newuser/newuser.docb +++ b/en/tutorials/newuser/newuser.docb @@ -1,943 +1,943 @@ - + For People New to Both FreeBSD and Unix Annelise Anderson
andrsn@andrsn.stanford.edu
August 15, 1997 Congratulations on installing FreeBSD! This introduction is for people new to both FreeBSD and Un*x—so it starts with basics. It assumes you're using version 2.0.5 or later of FreeBSD as distributed by Walnut Creek or FreeBSD.ORG, your system (for now) has a single user (you)—and you're probably pretty good with DOS/Windows or OS/2.
Logging in and Getting Out Log in (when you see login:) as a user you created during installation or as root. (Your FreeBSD installation will already have an account for root; root can go anywhere and do anything, including deleting essential files, so be careful!) The symbols % and # in the following stand for the prompt (yours may be different), with % indicating an ordinary user and # indicating root. To log out (and get a new login: prompt) type # exit as often as necessary. Yes, press enter after commands, and remember that Unix is case-sensitive—exit, not EXIT. To shut down the machine type: # /sbin/shutdown -h now Or to reboot type # /sbin/shutdown -r now or # /sbin/reboot You can also reboot with CtrlAltDelete. Give it a little time to do its work. This is equivalent to /sbin/reboot in recent releases of FreeBSD, and is much, much better than hitting the reset button. You don't want to have to reinstall this thing, do you? Adding A User with Root Privileges If you didn't create any users when you installed the system and are thus logged in as root, you should probably create a user now with # adduser The first time you use adduser, it might ask for some defaults to save. You might want to make the default shell csh instead of sh, if it suggests sh as the default. Otherwise just press enter to accept each default. These defaults are saved in /etc/adduser.conf, an editable file. Suppose you create a user jack with full name Jack Benimble. Give jack a password if security (even kids around who might pound on the keyboard) is an issue. When it asks you if you want to invite jack into other groups, type wheel Login group is ``jack''. Invite jack into other groups: wheel This will make it possible to log in as jack and use the su command to become root. Then you won't get scolded any more for logging in as root. You can quit adduser any time by typing CtrlC, and at the end you'll have a chance to approve your new user or simply type n for no. You might want to create a second new user (jill?) so that when you edit jack's login files, you'll have a hot spare in case something goes wrong. Once you've done this, use exit to get back to a login prompt and log in as jack. In general, it's a good idea to do as much work as possible as an ordinary user who doesn't have the power—and risk—of root. If you already created a user and you want the user to be able to su to root, you can log in as root and edit the file /etc/group, adding jack to the first line (the group wheel). But first you need to practice vi, the text editor--or use the simpler text editor, ee, installed on recent version of FreeBSD. To delete a user, use the rmuser command. Looking Around Logged in as an ordinary user, look around and try out some commands that will access the sources of help and information within FreeBSD. Here are some commands and what they do: id Tells you who you are! pwd Shows you where you are—the current working directory. ls Lists the files in the current directory. ls Lists the files in the current directory with a * after executables, a / after directories, and an @ after symbolic links. ls Lists the files in long format—size, date, permissions. ls Lists hidden dot files with the others. If you're root, thedot files show up without the switch. cd Changes directories. cd .. backs up one level; note the space after cd. cd /usr/local goes there. cd ~ goes to the home directory of the person logged in—e.g., /usr/home/jack. Try cd /cdrom, and then ls, to find out if your CDROM is mounted and working. view filename Lets you look at a file (named filename without changing it. Try view /etc/fstab. :q to quit. cat filename Displays filename on screen. If it's too long and you can see only the end of it, press ScrollLock and use the up-arrow to move backward; you can use ScrollLock with man pages too. Press ScrollLock again to quit scrolling. You might want to try cat on some of the dot files in your home directory—cat .cshrc, cat .login, cat .profile. You'll notice aliases in .cshrc for some of the ls commands (they're very convenient). You can create other aliases by editing .cshrc. You can make these aliases available to all users on the system by putting them in the system-wide csh configuration file, /etc/csh.cshrc. Getting Help and Information Here are some useful sources of help. Text stands for something of your choice that you type in—usually a command or filename. apropos text Everything containing string text in the whatis database. man text The man page for text. The major source of documentation for Un*x systems. man ls will tell you all the ways to use the ls command. Press Enter to move through text, Ctrlb to go back a page, Ctrlf to go forward, q or Ctrlc to quit. which text Tells you where in the user's path the command text is found. locate text All the paths where the string text is found. whatis text Tells you what the command text does and its man page. Typing whatis * will tell you about all the binaries in the current directory. whereis text Finds the file text, giving its full path. You might want to try using whatis on some common useful commands like cat, more, grep, mv, find, tar, chmod, chown, date, and script. more lets you read a page at a time as it does in DOS, e.g., ls -l | more or more filename. The * works as a wildcard—e.g., ls w* will show you files beginning with w. Are some of these not working very well? Both locate and whatis depend on a database that's rebuilt weekly. If your machine isn't going to be left on over the weekend (and running FreeBSD), you might want to run the commands for daily, weekly, and monthly maintenance now and then. Run them as root and give each one time to finish before you start the next one, for now. # /etc/daily output omitted # /etc/weekly output omitted # /etc/monthly output omitted If you get tired waiting, press AltF2 to get another virtual console, and log in again. After all, it's a multi-user, multi-tasking system. Nevertheless these commands will probably flash messages on your screen while they're running; you can type clear at the prompt to clear the screen. Once they've run, you might want to look at /var/mail/root and /var/log/messages. Basically running such commands is part of system administration—and as a single user of a Unix system, you're your own system administrator. Virtually everything you need to be root to do is system administration. Such responsibilities aren't covered very well even in those big fat books on Unix, which seem to devote a lot of space to pulling down menus in windows managers. You might want to get one of the two leading books on systems administration, either Evi Nemeth et.al.'s UNIX System Administration Handbook (Prentice-Hall, 1995, ISBN 0-13-15051-7)—the second edition with the red cover; or Æleen Frisch's Essential System Administration (O'Reilly & Associates, 1993, ISBN 0-937175-80-3). I used Nemeth. Editing Text To configure your system, you need to edit text files. Most of them will be in the /etc directory; and you'll need to su to root to be able to change them. You can use the easy ee, but in the long run the text editor vi is worth learning. There's an excellent tutorial on vi in /usr/src/contrib/nvi/docs/tutorial if you have that installed; otherwise you can get it by ftp to ftp.cdrom.com in the directory FreeBSD/FreeBSD-current/src/contrib/nvi/docs/tutorial. Before you edit a file, you should probably back it up. Suppose you want to edit /etc/rc.conf. You could just use cd /etc to get to the /etc directory and do: # cp rc.conf rc.conf.orig This would copy rc.conf to rc.conf.orig, and you could later copy rc.conf.orig to rc.conf to recover the original. But even better would be moving (renaming) and then copying back: # mv rc.conf rc.conf.orig # cp rc.conf.orig rc.conf because the mv command preserves the original date and owner of the file. You can now edit rc.conf. If you want the original back, you'd then mv rc.conf rc.conf.myedit (assuming you want to preserve your edited version) and then # mv rc.conf.orig rc.conf to put things back the way they were. To edit a file, type # vi filename Move through the text with the arrow keys. Esc (the escape key) puts vi in command mode. Here are some commands: x delete letter the cursor is on dd delete the entire line (even if it wraps on the screen) i insert text at the cursor a insert text after the cursor Once you type i or a, you can enter text. Esc puts you back in command mode where you can type :w to write your changes to disk and continue editing :wq to write and quit :q! to quit without saving changes /text to move the cursor to text; /Enter (the enter key) to find the next instance of text. G to go to the end of the file nG to go to line n in the file, where n is a number CtrlL to redraw the screen Ctrlb and Ctrlf go back and forward a screen, as they do with more and view. Practice with vi in your home directory by creating a new file with vi filename and adding and deleting text, saving the file, and calling it up again. vi delivers some surprises because it's really quite complex, and sometimes you'll inadvertently issue a command that will do something you don't expect. (Some people actually like vi—it's more powerful than DOS EDIT—find out about the :r command.) Use Esc one or more times to be sure you're in command mode and proceed from there when it gives you trouble, save often with :w, and use :q! to get out and start over (from your last :w) when you need to. Now you can cd to /etc, su to root, use vi to edit the file /etc/group, and add a user to wheel so the user has root privileges. Just add a comma and the user's login name to the end of the first line in the file, press Esc, and use :wq to write the file to disk and quit. Instantly effective. (You didn't put a space after the comma, did you?) Printing Files from DOS At this point you probably don't have the printer working, so here's a way to create a file from a man page, move it to a floppy, and then print it from DOS. Suppose you want to read carefully about changing permissions on files (pretty important). You can use the command man chmod to read about it. The command # man chmod | col -b > chmod.txt will remove formatting codes and send the man page to the chmod.txt file instead of showing it on your screen. Now put a dos-formatted diskette in your floppy drive a, su to root, and type # /sbin/mount -t msdos /dev/fd0 /mnt to mount the floppy drive on /mnt. Now (you no longer need to be root, and you can type exit to get back to being user jack) you can go to the directory where you created chmod.txt and copy the file to the floppy with: % cp chmod.txt /mnt and use ls /mnt to get a directory listing of /mnt, which should show the file chmod.txt. You might especially want to make a file from /sbin/dmesg by typing % /sbin/dmesg > dmesg.txt and copying dmesg.txt to the floppy. /sbin/dmesg is the boot log record, and it's useful to understand it because it shows what FreeBSD found when it booted up. If you ask questions on freebsd-questions@FreeBSD.ORG or on a USENET group—like FreeBSD isn't finding my tape drive, what do I do?—people will want to know what dmesg has to say. You can now dismount the floppy drive (as root) to get the disk out with # /sbin/umount /mnt and reboot to go to DOS. Copy these files to a DOS directory, call them up with DOS EDIT, Windows Notepad or Wordpad, or a word processor, make a minor change so the file has to be saved, and print as you normally would from DOS or Windows. Hope it works! man pages come out best if printed with the dos print command. (Copying files from FreeBSD to a mounted dos partition is in some cases still a little risky.) Getting the printer printing from FreeBSD involves creating an appropriate entry in /etc/printcap and creating a matching spool directory in /var/spool/output. If your printer is on lpt0 (what dos calls LPT1), you may only need to go to /var/spool/output and (as root) create the directory lpd by typing: mkdir lpd, if it doesn't already exist. Then the printer should respond if it's turned on when the system is booted, and lp or lpr should send a file to the printer. Whether or not the file actually prints depends on configuring it, which is covered in the FreeBSD +URL="../../handbook/handbook.html">FreeBSD handbook. Other Useful Commands df shows file space and mounted systems. ps aux shows processes running. ps ax is a narrower form. rm filename remove filename. rm -R dir removes a directory dir and all subdirectories—careful! ls -R lists files in the current directory and all subdirectories; I used a variant, ls -AFR > where.txt, to get a list of all the files in / and (separately) /usr before I found better ways to find files. passwd to change user's password (or root's password) man hier man page on the Unix file system Use find to locate filename in /usr or any of its subdirectories with % find /usr -name "filename" You can use * as a wildcard in "filename" (which should be in quotes). If you tell find to search in / instead of /usr it will look for the file(s) on all mounted file systems, including the CDROM and the dos partition. An excellent book that explains Unix commands and utilities is Abrahams & Larson, Unix for the Impatient (2nd ed., Addison-Wesley, 1996). There's also a lot of Unix information on the Internet. Try the Unix Reference Desk. Next Steps You should now have the tools you need to get around and edit files, so you can get everything up and running. There is a great deal of information in the FreeBSD handbook (which is probably on your hard drive) and FreeBSD's web site. A wide variety of packages and ports are on the Walnut Creek CDROM as well as the web site. The handbook tells you more about how to use them (get the package if it exists, with pkg_add /cdrom/packages/All/packagename, where packagename is the filename of the package). The cdrom has lists of the packages and ports with brief descriptions in cdrom/packages/index, cdrom/packages/index.txt, and cdrom/ports/index, with fuller descriptions in /cdrom/ports/*/*/pkg/DESCR, where the *s represent subdirectories of kinds of programs and program names respectively. If you find the handbook too sophisticated (what with lndir and all) on installing ports from the cdrom, here's what usually works: Find the port you want, say kermit. There will be a directory for it on the cdrom. Copy the subdirectory to /usr/local (a good place for software you add that should be available to all users) with: # cp -R /cdrom/ports/comm/kermit /usr/local This should result in a /usr/local/kermit subdirectory that has all the files that the kermit subdirectory on the CDROM has. Next, create the directory /usr/ports/distfiles if it doesn't already exist using mkdir. Now check check /cdrom/ports/distfiles for a file with a name that indicates it's the port you want. Copy that file to /usr/ports/distfiles; in recent versions you can skip this step, as FreeBSD will do it for you. In the case of kermit, there is no distfile. Then cd to the subdirectory of /usr/local/kermit that has the file Makefile. Type # make all install During this process the port will ftp to get any compressed files it needs that it didn't find on the cdrom or in /usr/ports/distfiles. If you don't have your network running yet and there was no file for the port in /cdrom/ports/distfiles, you will have to get the distfile using another machine and copy it to /usr/ports/distfiles from a floppy or your dos partition. Read Makefile (with cat or more or view) to find out where to go (the master distribution site) to get the file and what its name is. Its name will be truncated when downloaded to DOS, and after you get it into /usr/ports/distfiles you'll have to rename it (with the mv command) to its original name so it can be found. (Use binary file transfers!) Then go back to /usr/local/kermit, find the directory with Makefile, and type make all install. The other thing that happens when installing ports or packages is that some other program is needed. If the installation stops with a message can't find unzip or whatever, you might need to install the package or port for unzip before you continue. Once it's installed type rehash to make FreeBSD reread the files in the path so it knows what's there. (If you get a lot of path not found messages when you use whereis or which, you might want to make additions to the list of directories in the path statement in .cshrc in your home directory. The path statement in Unix does the same kind of work it does in DOS, except the current directory is not (by default) in the path for security reasons; if the command you want is in the directory you're in, you need to type ./ before the command to make it work; no space after the slash.) You might want to get the most recent version of Netscape from their ftp site. (Netscape requires the X Window System.) There's now a FreeBSD version, so look around carefully. Just use gunzip filename and tar xvf filename on it, move the binary to /usr/local/bin or some other place binaries are kept, rehash, and then put the following lines in .cshrc in each user's home directory or (easier) in /etc/csh.cshrc, the system-wide csh start-up file: setenv XKEYSYMDB /usr/X11R6/lib/X11/XKeysymDB setenv XNLSPATH /usr/X11R6/lib/X11/nls This assumes that the file XKeysymDB and the directory nls are in /usr/X11R6/lib/X11; if they're not, find them and put them there. If you originally got Netscape as a port using the CDROM (or ftp), don't replace /usr/local/bin/netscape with the new netscape binary; this is just a shell script that sets up the environmental variables for you. Instead rename the new binary to netscape.bin and replace the old binary, which is /usr/local/lib/netscape/netscape.bin. Your Working Environment Your shell is the most important part of your working environment. In DOS, the usual shell is command.com. The shell is what interprets the commands you type on the command line, and thus communicates with the rest of the operating system. You can also write shell scripts, which are like DOS batch files: a series of commands to be run without your intervention. Two shells come installed with FreeBSD: csh and sh. csh is good for command-line work, but scripts should be written with sh (or bash). You can find out what shell you have by typing echo $SHELL. The csh shell is okay, but tcsh does everything csh does and more. It It allows you to recall commands with the arrow keys and edit them. It has tab-key completion of filenames (csh uses the escape key), and it lets you switch to the directory you were last in with cd -. It's also much easier to alter your prompt with tcsh. It makes life a lot easier. Here are the three steps for installing a new shell: 1. Install the shell as a port or a package, just as you would any other port or package. Use rehash and which tcsh (assuming you're installing tcsh) to make sure it got installed. 2. As root, edit /etc/shells, adding a line in the file for the new shell, in this case /usr/local/bin/tcsh, and save the file. (Some ports may do this for you.) 3. Use the chsh command to change your shell to tcsh permanently, or type tcsh at the prompt to change your shell without logging in again. Note: It can be dangerous to change root's shell to something other than sh or csh on early versions of FreeBSD and many other versions of Unix; you may not have a working shell when the system puts you into single user mode. The solution is to use su -m to become root, which will give you the tcsh as root, because the shell is part of the environment. You can make this permanent by adding it to your .tcshrc file as an alias with alias su su -m. When tcsh starts up, it will read the /etc/csh.cshrc and /etc/csh.login files, as does csh. It will also read the .login file in your home directory and the .cshrc file as well, unless you provide a .tcshrc file. This you can do by simply copying .cshrc to .tcshrc. Now that you've installed tcsh, you can adjust your prompt. You can find the details in the manual page for tcsh, but here is a line to put in your .tcshrc that will tell you how many commands you have typed, what time it is, and what directory you are in. It also produces a > if you're an ordinary user and a # if you're root, but tsch will do that in any case: set prompt = "%h %t %~ %# " This should go in the same place as the existing set prompt line if there is one, or under "if($?prompt) then" if not. Comment out the old line; you can always switch back to it if you prefer it. Don't forget the spaces and quotes. You can get the .tcshrc reread by typing source .tcshrc. You can get a listing of other environmental variables that have been set by typing env at the prompt. The result will show you your default editor, pager, and terminal type, among possibly many others. A useful command if you log in from a remote location and can't run a program because the terminal isn't capable is setenv TERM vt100. Other As root, you can dismount the CDROM with /sbin/umount /cdrom, take it out of the drive, insert another one, and mount it with /sbin/mount_cd9660 /dev/cd0a /cdrom assuming cd0a is the device name for your CDROM drive. The most recent versions of FreeBSD let you mount the cdrom with just /sbin/mount /cdrom. Using the live file system—the second of FreeBSD's CDROM disks—is useful if you've got limited space. What is on the live file system varies from release to release. You might try playing games from the cdrom. This involves using lndir, which gets installed with the X Window System, to tell the program(s) where to find the necessary files, because they're in the /cdrom file system instead of in /usr and its subdirectories, which is where they're expected to be. Read man lndir. Comments Welcome If you use this guide I'd be interested in knowing where it was unclear and what was left out that you think should be included, and if it was helpful. My thanks to Eugene W. Stark, professor of computer science at SUNY-Stony Brook, and John Fieber for helpful comments. Annelise Anderson, andrsn@andrsn.stanford.edu
diff --git a/en_US.ISO8859-1/articles/new-users/article.sgml b/en_US.ISO8859-1/articles/new-users/article.sgml index 67568b5590..9c3baeb6b5 100644 --- a/en_US.ISO8859-1/articles/new-users/article.sgml +++ b/en_US.ISO8859-1/articles/new-users/article.sgml @@ -1,943 +1,943 @@ - + For People New to Both FreeBSD and Unix Annelise Anderson
andrsn@andrsn.stanford.edu
August 15, 1997 Congratulations on installing FreeBSD! This introduction is for people new to both FreeBSD and Un*x—so it starts with basics. It assumes you're using version 2.0.5 or later of FreeBSD as distributed by Walnut Creek or FreeBSD.ORG, your system (for now) has a single user (you)—and you're probably pretty good with DOS/Windows or OS/2.
Logging in and Getting Out Log in (when you see login:) as a user you created during installation or as root. (Your FreeBSD installation will already have an account for root; root can go anywhere and do anything, including deleting essential files, so be careful!) The symbols % and # in the following stand for the prompt (yours may be different), with % indicating an ordinary user and # indicating root. To log out (and get a new login: prompt) type # exit as often as necessary. Yes, press enter after commands, and remember that Unix is case-sensitive—exit, not EXIT. To shut down the machine type: # /sbin/shutdown -h now Or to reboot type # /sbin/shutdown -r now or # /sbin/reboot You can also reboot with CtrlAltDelete. Give it a little time to do its work. This is equivalent to /sbin/reboot in recent releases of FreeBSD, and is much, much better than hitting the reset button. You don't want to have to reinstall this thing, do you? Adding A User with Root Privileges If you didn't create any users when you installed the system and are thus logged in as root, you should probably create a user now with # adduser The first time you use adduser, it might ask for some defaults to save. You might want to make the default shell csh instead of sh, if it suggests sh as the default. Otherwise just press enter to accept each default. These defaults are saved in /etc/adduser.conf, an editable file. Suppose you create a user jack with full name Jack Benimble. Give jack a password if security (even kids around who might pound on the keyboard) is an issue. When it asks you if you want to invite jack into other groups, type wheel Login group is ``jack''. Invite jack into other groups: wheel This will make it possible to log in as jack and use the su command to become root. Then you won't get scolded any more for logging in as root. You can quit adduser any time by typing CtrlC, and at the end you'll have a chance to approve your new user or simply type n for no. You might want to create a second new user (jill?) so that when you edit jack's login files, you'll have a hot spare in case something goes wrong. Once you've done this, use exit to get back to a login prompt and log in as jack. In general, it's a good idea to do as much work as possible as an ordinary user who doesn't have the power—and risk—of root. If you already created a user and you want the user to be able to su to root, you can log in as root and edit the file /etc/group, adding jack to the first line (the group wheel). But first you need to practice vi, the text editor--or use the simpler text editor, ee, installed on recent version of FreeBSD. To delete a user, use the rmuser command. Looking Around Logged in as an ordinary user, look around and try out some commands that will access the sources of help and information within FreeBSD. Here are some commands and what they do: id Tells you who you are! pwd Shows you where you are—the current working directory. ls Lists the files in the current directory. ls Lists the files in the current directory with a * after executables, a / after directories, and an @ after symbolic links. ls Lists the files in long format—size, date, permissions. ls Lists hidden dot files with the others. If you're root, thedot files show up without the switch. cd Changes directories. cd .. backs up one level; note the space after cd. cd /usr/local goes there. cd ~ goes to the home directory of the person logged in—e.g., /usr/home/jack. Try cd /cdrom, and then ls, to find out if your CDROM is mounted and working. view filename Lets you look at a file (named filename without changing it. Try view /etc/fstab. :q to quit. cat filename Displays filename on screen. If it's too long and you can see only the end of it, press ScrollLock and use the up-arrow to move backward; you can use ScrollLock with man pages too. Press ScrollLock again to quit scrolling. You might want to try cat on some of the dot files in your home directory—cat .cshrc, cat .login, cat .profile. You'll notice aliases in .cshrc for some of the ls commands (they're very convenient). You can create other aliases by editing .cshrc. You can make these aliases available to all users on the system by putting them in the system-wide csh configuration file, /etc/csh.cshrc. Getting Help and Information Here are some useful sources of help. Text stands for something of your choice that you type in—usually a command or filename. apropos text Everything containing string text in the whatis database. man text The man page for text. The major source of documentation for Un*x systems. man ls will tell you all the ways to use the ls command. Press Enter to move through text, Ctrlb to go back a page, Ctrlf to go forward, q or Ctrlc to quit. which text Tells you where in the user's path the command text is found. locate text All the paths where the string text is found. whatis text Tells you what the command text does and its man page. Typing whatis * will tell you about all the binaries in the current directory. whereis text Finds the file text, giving its full path. You might want to try using whatis on some common useful commands like cat, more, grep, mv, find, tar, chmod, chown, date, and script. more lets you read a page at a time as it does in DOS, e.g., ls -l | more or more filename. The * works as a wildcard—e.g., ls w* will show you files beginning with w. Are some of these not working very well? Both locate and whatis depend on a database that's rebuilt weekly. If your machine isn't going to be left on over the weekend (and running FreeBSD), you might want to run the commands for daily, weekly, and monthly maintenance now and then. Run them as root and give each one time to finish before you start the next one, for now. # /etc/daily output omitted # /etc/weekly output omitted # /etc/monthly output omitted If you get tired waiting, press AltF2 to get another virtual console, and log in again. After all, it's a multi-user, multi-tasking system. Nevertheless these commands will probably flash messages on your screen while they're running; you can type clear at the prompt to clear the screen. Once they've run, you might want to look at /var/mail/root and /var/log/messages. Basically running such commands is part of system administration—and as a single user of a Unix system, you're your own system administrator. Virtually everything you need to be root to do is system administration. Such responsibilities aren't covered very well even in those big fat books on Unix, which seem to devote a lot of space to pulling down menus in windows managers. You might want to get one of the two leading books on systems administration, either Evi Nemeth et.al.'s UNIX System Administration Handbook (Prentice-Hall, 1995, ISBN 0-13-15051-7)—the second edition with the red cover; or Æleen Frisch's Essential System Administration (O'Reilly & Associates, 1993, ISBN 0-937175-80-3). I used Nemeth. Editing Text To configure your system, you need to edit text files. Most of them will be in the /etc directory; and you'll need to su to root to be able to change them. You can use the easy ee, but in the long run the text editor vi is worth learning. There's an excellent tutorial on vi in /usr/src/contrib/nvi/docs/tutorial if you have that installed; otherwise you can get it by ftp to ftp.cdrom.com in the directory FreeBSD/FreeBSD-current/src/contrib/nvi/docs/tutorial. Before you edit a file, you should probably back it up. Suppose you want to edit /etc/rc.conf. You could just use cd /etc to get to the /etc directory and do: # cp rc.conf rc.conf.orig This would copy rc.conf to rc.conf.orig, and you could later copy rc.conf.orig to rc.conf to recover the original. But even better would be moving (renaming) and then copying back: # mv rc.conf rc.conf.orig # cp rc.conf.orig rc.conf because the mv command preserves the original date and owner of the file. You can now edit rc.conf. If you want the original back, you'd then mv rc.conf rc.conf.myedit (assuming you want to preserve your edited version) and then # mv rc.conf.orig rc.conf to put things back the way they were. To edit a file, type # vi filename Move through the text with the arrow keys. Esc (the escape key) puts vi in command mode. Here are some commands: x delete letter the cursor is on dd delete the entire line (even if it wraps on the screen) i insert text at the cursor a insert text after the cursor Once you type i or a, you can enter text. Esc puts you back in command mode where you can type :w to write your changes to disk and continue editing :wq to write and quit :q! to quit without saving changes /text to move the cursor to text; /Enter (the enter key) to find the next instance of text. G to go to the end of the file nG to go to line n in the file, where n is a number CtrlL to redraw the screen Ctrlb and Ctrlf go back and forward a screen, as they do with more and view. Practice with vi in your home directory by creating a new file with vi filename and adding and deleting text, saving the file, and calling it up again. vi delivers some surprises because it's really quite complex, and sometimes you'll inadvertently issue a command that will do something you don't expect. (Some people actually like vi—it's more powerful than DOS EDIT—find out about the :r command.) Use Esc one or more times to be sure you're in command mode and proceed from there when it gives you trouble, save often with :w, and use :q! to get out and start over (from your last :w) when you need to. Now you can cd to /etc, su to root, use vi to edit the file /etc/group, and add a user to wheel so the user has root privileges. Just add a comma and the user's login name to the end of the first line in the file, press Esc, and use :wq to write the file to disk and quit. Instantly effective. (You didn't put a space after the comma, did you?) Printing Files from DOS At this point you probably don't have the printer working, so here's a way to create a file from a man page, move it to a floppy, and then print it from DOS. Suppose you want to read carefully about changing permissions on files (pretty important). You can use the command man chmod to read about it. The command # man chmod | col -b > chmod.txt will remove formatting codes and send the man page to the chmod.txt file instead of showing it on your screen. Now put a dos-formatted diskette in your floppy drive a, su to root, and type # /sbin/mount -t msdos /dev/fd0 /mnt to mount the floppy drive on /mnt. Now (you no longer need to be root, and you can type exit to get back to being user jack) you can go to the directory where you created chmod.txt and copy the file to the floppy with: % cp chmod.txt /mnt and use ls /mnt to get a directory listing of /mnt, which should show the file chmod.txt. You might especially want to make a file from /sbin/dmesg by typing % /sbin/dmesg > dmesg.txt and copying dmesg.txt to the floppy. /sbin/dmesg is the boot log record, and it's useful to understand it because it shows what FreeBSD found when it booted up. If you ask questions on freebsd-questions@FreeBSD.ORG or on a USENET group—like FreeBSD isn't finding my tape drive, what do I do?—people will want to know what dmesg has to say. You can now dismount the floppy drive (as root) to get the disk out with # /sbin/umount /mnt and reboot to go to DOS. Copy these files to a DOS directory, call them up with DOS EDIT, Windows Notepad or Wordpad, or a word processor, make a minor change so the file has to be saved, and print as you normally would from DOS or Windows. Hope it works! man pages come out best if printed with the dos print command. (Copying files from FreeBSD to a mounted dos partition is in some cases still a little risky.) Getting the printer printing from FreeBSD involves creating an appropriate entry in /etc/printcap and creating a matching spool directory in /var/spool/output. If your printer is on lpt0 (what dos calls LPT1), you may only need to go to /var/spool/output and (as root) create the directory lpd by typing: mkdir lpd, if it doesn't already exist. Then the printer should respond if it's turned on when the system is booted, and lp or lpr should send a file to the printer. Whether or not the file actually prints depends on configuring it, which is covered in the FreeBSD +URL="../../handbook/handbook.html">FreeBSD handbook. Other Useful Commands df shows file space and mounted systems. ps aux shows processes running. ps ax is a narrower form. rm filename remove filename. rm -R dir removes a directory dir and all subdirectories—careful! ls -R lists files in the current directory and all subdirectories; I used a variant, ls -AFR > where.txt, to get a list of all the files in / and (separately) /usr before I found better ways to find files. passwd to change user's password (or root's password) man hier man page on the Unix file system Use find to locate filename in /usr or any of its subdirectories with % find /usr -name "filename" You can use * as a wildcard in "filename" (which should be in quotes). If you tell find to search in / instead of /usr it will look for the file(s) on all mounted file systems, including the CDROM and the dos partition. An excellent book that explains Unix commands and utilities is Abrahams & Larson, Unix for the Impatient (2nd ed., Addison-Wesley, 1996). There's also a lot of Unix information on the Internet. Try the Unix Reference Desk. Next Steps You should now have the tools you need to get around and edit files, so you can get everything up and running. There is a great deal of information in the FreeBSD handbook (which is probably on your hard drive) and FreeBSD's web site. A wide variety of packages and ports are on the Walnut Creek CDROM as well as the web site. The handbook tells you more about how to use them (get the package if it exists, with pkg_add /cdrom/packages/All/packagename, where packagename is the filename of the package). The cdrom has lists of the packages and ports with brief descriptions in cdrom/packages/index, cdrom/packages/index.txt, and cdrom/ports/index, with fuller descriptions in /cdrom/ports/*/*/pkg/DESCR, where the *s represent subdirectories of kinds of programs and program names respectively. If you find the handbook too sophisticated (what with lndir and all) on installing ports from the cdrom, here's what usually works: Find the port you want, say kermit. There will be a directory for it on the cdrom. Copy the subdirectory to /usr/local (a good place for software you add that should be available to all users) with: # cp -R /cdrom/ports/comm/kermit /usr/local This should result in a /usr/local/kermit subdirectory that has all the files that the kermit subdirectory on the CDROM has. Next, create the directory /usr/ports/distfiles if it doesn't already exist using mkdir. Now check check /cdrom/ports/distfiles for a file with a name that indicates it's the port you want. Copy that file to /usr/ports/distfiles; in recent versions you can skip this step, as FreeBSD will do it for you. In the case of kermit, there is no distfile. Then cd to the subdirectory of /usr/local/kermit that has the file Makefile. Type # make all install During this process the port will ftp to get any compressed files it needs that it didn't find on the cdrom or in /usr/ports/distfiles. If you don't have your network running yet and there was no file for the port in /cdrom/ports/distfiles, you will have to get the distfile using another machine and copy it to /usr/ports/distfiles from a floppy or your dos partition. Read Makefile (with cat or more or view) to find out where to go (the master distribution site) to get the file and what its name is. Its name will be truncated when downloaded to DOS, and after you get it into /usr/ports/distfiles you'll have to rename it (with the mv command) to its original name so it can be found. (Use binary file transfers!) Then go back to /usr/local/kermit, find the directory with Makefile, and type make all install. The other thing that happens when installing ports or packages is that some other program is needed. If the installation stops with a message can't find unzip or whatever, you might need to install the package or port for unzip before you continue. Once it's installed type rehash to make FreeBSD reread the files in the path so it knows what's there. (If you get a lot of path not found messages when you use whereis or which, you might want to make additions to the list of directories in the path statement in .cshrc in your home directory. The path statement in Unix does the same kind of work it does in DOS, except the current directory is not (by default) in the path for security reasons; if the command you want is in the directory you're in, you need to type ./ before the command to make it work; no space after the slash.) You might want to get the most recent version of Netscape from their ftp site. (Netscape requires the X Window System.) There's now a FreeBSD version, so look around carefully. Just use gunzip filename and tar xvf filename on it, move the binary to /usr/local/bin or some other place binaries are kept, rehash, and then put the following lines in .cshrc in each user's home directory or (easier) in /etc/csh.cshrc, the system-wide csh start-up file: setenv XKEYSYMDB /usr/X11R6/lib/X11/XKeysymDB setenv XNLSPATH /usr/X11R6/lib/X11/nls This assumes that the file XKeysymDB and the directory nls are in /usr/X11R6/lib/X11; if they're not, find them and put them there. If you originally got Netscape as a port using the CDROM (or ftp), don't replace /usr/local/bin/netscape with the new netscape binary; this is just a shell script that sets up the environmental variables for you. Instead rename the new binary to netscape.bin and replace the old binary, which is /usr/local/lib/netscape/netscape.bin. Your Working Environment Your shell is the most important part of your working environment. In DOS, the usual shell is command.com. The shell is what interprets the commands you type on the command line, and thus communicates with the rest of the operating system. You can also write shell scripts, which are like DOS batch files: a series of commands to be run without your intervention. Two shells come installed with FreeBSD: csh and sh. csh is good for command-line work, but scripts should be written with sh (or bash). You can find out what shell you have by typing echo $SHELL. The csh shell is okay, but tcsh does everything csh does and more. It It allows you to recall commands with the arrow keys and edit them. It has tab-key completion of filenames (csh uses the escape key), and it lets you switch to the directory you were last in with cd -. It's also much easier to alter your prompt with tcsh. It makes life a lot easier. Here are the three steps for installing a new shell: 1. Install the shell as a port or a package, just as you would any other port or package. Use rehash and which tcsh (assuming you're installing tcsh) to make sure it got installed. 2. As root, edit /etc/shells, adding a line in the file for the new shell, in this case /usr/local/bin/tcsh, and save the file. (Some ports may do this for you.) 3. Use the chsh command to change your shell to tcsh permanently, or type tcsh at the prompt to change your shell without logging in again. Note: It can be dangerous to change root's shell to something other than sh or csh on early versions of FreeBSD and many other versions of Unix; you may not have a working shell when the system puts you into single user mode. The solution is to use su -m to become root, which will give you the tcsh as root, because the shell is part of the environment. You can make this permanent by adding it to your .tcshrc file as an alias with alias su su -m. When tcsh starts up, it will read the /etc/csh.cshrc and /etc/csh.login files, as does csh. It will also read the .login file in your home directory and the .cshrc file as well, unless you provide a .tcshrc file. This you can do by simply copying .cshrc to .tcshrc. Now that you've installed tcsh, you can adjust your prompt. You can find the details in the manual page for tcsh, but here is a line to put in your .tcshrc that will tell you how many commands you have typed, what time it is, and what directory you are in. It also produces a > if you're an ordinary user and a # if you're root, but tsch will do that in any case: set prompt = "%h %t %~ %# " This should go in the same place as the existing set prompt line if there is one, or under "if($?prompt) then" if not. Comment out the old line; you can always switch back to it if you prefer it. Don't forget the spaces and quotes. You can get the .tcshrc reread by typing source .tcshrc. You can get a listing of other environmental variables that have been set by typing env at the prompt. The result will show you your default editor, pager, and terminal type, among possibly many others. A useful command if you log in from a remote location and can't run a program because the terminal isn't capable is setenv TERM vt100. Other As root, you can dismount the CDROM with /sbin/umount /cdrom, take it out of the drive, insert another one, and mount it with /sbin/mount_cd9660 /dev/cd0a /cdrom assuming cd0a is the device name for your CDROM drive. The most recent versions of FreeBSD let you mount the cdrom with just /sbin/mount /cdrom. Using the live file system—the second of FreeBSD's CDROM disks—is useful if you've got limited space. What is on the live file system varies from release to release. You might try playing games from the cdrom. This involves using lndir, which gets installed with the X Window System, to tell the program(s) where to find the necessary files, because they're in the /cdrom file system instead of in /usr and its subdirectories, which is where they're expected to be. Read man lndir. Comments Welcome If you use this guide I'd be interested in knowing where it was unclear and what was left out that you think should be included, and if it was helpful. My thanks to Eugene W. Stark, professor of computer science at SUNY-Stony Brook, and John Fieber for helpful comments. Annelise Anderson, andrsn@andrsn.stanford.edu
diff --git a/en_US.ISO8859-1/articles/programming-tools/article.sgml b/en_US.ISO8859-1/articles/programming-tools/article.sgml index addd185ee8..65e1f87d26 100644 --- a/en_US.ISO8859-1/articles/programming-tools/article.sgml +++ b/en_US.ISO8859-1/articles/programming-tools/article.sgml @@ -1,1835 +1,1835 @@ - + A User's Guide to FreeBSD Programming Tools James Raynard
jraynard@freebsd.org
August 17, 1997 1997 James Raynard This document is an introduction to using some of the programming tools supplied with FreeBSD, although much of it will be applicable to many other versions of Unix. It does not attempt to describe coding in any detail. Most of the document assumes little or no previous programming knowledge, although it is hoped that most programmers will find something of value in it
Introduction<anchor id=foo> FreeBSD offers an excellent development environment. Compilers for C, C++, and Fortran and an assembler come with the basic system, not to mention a Perl interpreter and classic Unix tools such as sed and awk. If that is not enough, there are many more compilers and interpreters in the Ports collection. FreeBSD is very compatible with standards such as POSIX and ANSI C, as well with its own BSD heritage, so it is possible to write applications that will compile and run with little or no modification on a wide range of platforms. However, all this power can be rather overwhelming at first if you've never written programs on a Unix platform before. This document aims to help you get up and running, without getting too deeply into more advanced topics. The intention is that this document should give you enough of the basics to be able to make some sense of the documentation. Most of the document requires little or no knowledge of programming, although it does assume a basic competence with using Unix and a willingness to learn! Introduction to Programming A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to perform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can give these instructions, or commands as they are usually called. One way uses an interpreter, the other a compiler. As human languages are too difficult for a computer to understand in an unambiguous way, commands are usually written in one or other languages specially designed for the purpose. Interpreters With an interpreter, the language comes as an environment, where you type in commands at a prompt and the environment executes them for you. For more complicated programs, you can type the commands into a file and get the interpreter to load the file and execute the commands in it. If anything goes wrong, many interpreters will drop you into a debugger to help you track down the problem. The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected readily. The biggest disadvantage comes when you want to share your programs with someone. They must have the same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. Also users may not appreciate being thrown into a debugger if they press the wrong key! From a performance point of view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers. In my opinion, interpreted languages are the best way to start if you have not done any programming before. This kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also be argued that the Unix shell (sh, csh) is itself an interpreter, and many people do in fact write shell scripts to help with various housekeeping tasks on their machine. Indeed, part of the original Unix philosophy was to provide lots of small utility programs that could be linked together in shell scripts to perform useful tasks. Interpreters available with FreeBSD Here is a list of interpreters that are available as FreeBSD packages, with a brief discussion of some of the more popular interpreted languages. To get one of these packages, all you need to do is to click on the hotlink for the package, then run $ pkg_add package name as root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later system for the package to work! BASIC Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching University students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been the first programming language for many programmers. It's also the foundation for Visual Basic. The Bywater Basic Interpreter and the Phil Cockroft's Basic Interpreter (formerly Rabbit Basic) are available as FreeBSD FreeBSD packages Lisp A language that was developed in the late 1950s as an alternative to the number-crunching languages that were popular at the time. Instead of being based on numbers, Lisp is based on lists; in fact the name is short for List Processing. Very popular in AI (Artificial Intelligence) circles. Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. FreeBSD has GNU Common Lisp available as a package. Perl Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. Version 4, which is probably still the most widely-used version, comes with FreeBSD; the newer Perl Version 5 is available as a package. Scheme A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it is simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to be used in research work. FreeBSD has packages of the Elk Scheme Interpreter, the MIT Scheme Interpreter and the SCM Scheme Interpreter. Icon The Icon Programming Language. Logo Brian Harvey's LOGO Interpreter. Python The Python Object-Oriented Programming Language Compilers Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then run the compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the editor; if it did compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works properly.If you run it in the shell, you may get a core dump. Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things which are very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating system—or even writing your own operating system! It's also useful if you need to write very efficient code, as the compiler can take its time and optimise the code, which would not be acceptable in an interpreter. And distributing a program written for a compiler is usually more straightforward than one written for an interpreter—you can just give them a copy of the executable, assuming they have the same operating system as you. Compiled languages include Pascal, C and C++. C and C++ are rather unforgiving languages, and best suited to more experienced programmers; Pascal, on the other hand, was designed as an educational language, and is quite a good language to start with. Unfortunately, FreeBSD doesn't have any Pascal support, except for a Pascal-to-C converter in the ports. As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not have an IDE as such; however it is possible to use Emacs for this purpose. This is discussed in . Compiling with <command>cc</command> This section deals only with the GNU compiler for C and C++, since that comes with the base FreeBSD system. It can be invoked by either cc or gcc. The details of producing a program with an interpreter vary considerably between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. Once you've written your masterpiece, the next step is to convert it into something that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which is done by a separate program. Pre-process your source code to remove comments and do other tricks like expanding macros in C. Check the syntax of your code to see if you have obeyed the rules of the language. If you have not, it will complain! Convert the source code into assembly language—this is very close to machine code, but still understandable by humans. Allegedly.To be strictly accurate, cc converts the source code into its own, machine-independent p-code instead of assembly language at this stage. Convert the assembly language into machine code—yep, we are talking bits and bytes, ones and zeros here. Check that you have used things like functions and global variables in a consistent way. For example, if you have called a non-existent function, it will complain. If you are trying to produce an executable from several source code files, work out how to fit them all together. Work out how to produce something that the system's run-time loader will be able to load into memory and run. Finally, write the executable on the file system. The word compiling is often used to refer to just steps 1 to 4—the others are referred to as linking. Sometimes step 1 is referred to as pre-processing and steps 3-4 as assembling. Fortunately, almost all this detail is hidden from you, as cc is a front end that manages calling all these programs with the right arguments for you; simply typing $ cc foobar.c will cause foobar.c to be compiled by all the steps above. If you have more than one file to compile, just do something like $ cc foo.c bar.c Note that the syntax checking is just that—checking the syntax. It will not check for any logical mistakes you may have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort.In case you didn't know, a binary sort is an efficient way of sorting things into order and a bubble sort isn't. There are lots and lots of options for cc, which are all in the man page. Here are a few of the most important ones, with examples of how to use them. The output name of the file. If you do not use this option, cc will produce an executable called a.out.The reasons for this are buried in the mists of history. $ cc foobar.c executable is a.out $ cc -o foobar foobar.c executable is foobar Just compile the file, do not link it. Useful for toy programs where you just want to check the syntax, or if you are using a Makefile. $ cc -c foobar.c This will produce an object file (not an executable) called foobar.o. This can be linked together with other object files into an executable. Create a debug version of the executable. This makes the compiler put information into the executable about which line of which source file corresponds to which function call. A debugger can use this information to show the source code as you step through the program, which is very useful; the disadvantage is that all this extra information makes the program much bigger. Normally, you compile with while you are developing a program and then compile a release version without when you're satisfied it works properly. $ cc -g foobar.c This will produce a debug version of the program.Note, we didn't use the flag to specify the executable name, so we will get an executable called a.out. Producing a debug version called foobar is left as an exercise for the reader! Create an optimised version of the executable. The compiler performs various clever tricks to try and produce an executable that runs faster than normal. You can add a number after the to specify a higher level of optimisation, but this often exposes bugs in the compiler's optimiser. For instance, the version of cc that comes with the 2.1.0 release of FreeBSD is known to produce bad code with the option in some circumstances. Optimisation is usually only turned on when compiling a release version. $ cc -O -o foobar foobar.c This will produce an optimised version of foobar. The following three flags will force cc to check that your code complies to the relevant international standard, often referred to as the ANSI standard, though strictly speaking it is an ISO standard. Enable all the warnings which the authors of cc believe are worthwhile. Despite the name, it will not enable all the warnings cc is capable of. Turn off most, but not all, of the non-ANSI C features provided by cc. Despite the name, it does not guarantee strictly that your code will comply to the standard. Turn off all cc's non-ANSI C features. Without these flags, cc will allow you to use some of its non-standard extensions to the standard. Some of these are very useful, but will not work with other compilers—in fact, one of the main aims of the standard is to allow people to write code that will work with any compiler on any system. This is known as portable code. Generally, you should try to make your code as portable as possible, as otherwise you may have to completely re-write the program later to get it to work somewhere else—and who knows what you may be using in a few years time? $ cc -Wall -ansi -pedantic -o foobar foobar.c This will produce an executable foobar after checking foobar.c for standard compliance. Specify a function library to be used during when linking. The most common example of this is when compiling a program that uses some of the mathematical functions in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell the compiler to add it. The rule is that if the library is called libsomething.a, you give cc the argument . For example, the math library is libm.a, so you give cc the argument . A common gotcha with the math library is that it has to be the last library on the command line. $ cc -o foobar foobar.c -lm This will link the math library functions into foobar. If you are compiling C++ code, you need to add , or if you are using FreeBSD 2.2 or later, to the command line argument to link the C++ library functions. Alternatively, you can run c++ instead of cc, which does this for you. c++ can also be invoked as g++ on FreeBSD. $ cc -o foobar foobar.cc -lg++ For FreeBSD 2.1.6 and earlier $ cc -o foobar foobar.cc -lstdc++ For FreeBSD 2.2 and later $ c++ -o foobar foobar.cc Each of these will both produce an executable foobar from the C++ source file foobar.cc. Note that, on Unix systems, C++ source files traditionally end in .C, .cxx or .cc, rather than the MS-DOS style .cpp (which was already used for something else). gcc used to rely on this to work out what kind of compiler to use on the source file; however, this restriction no longer applies, so you may now call your C++ files .cpp with impunity! Common <command>cc</command> Queries and Problems Q. I am trying to write a program which uses the sin() function and I get an error like this. What does it mean? /var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment A. When using mathematical functions like sin(), you have to tell cc to link in the math library, like so: $ cc -o foobar foobar.c -lm Q. All right, I wrote this simple program to practice using . All it does is raise 2.1 to the power of 6. #include <stdio.h> int main() { float f; f = pow(2.1, 6); printf("2.1 ^ 6 = %f\n", f); return 0; } and I compiled it as: $ cc temp.c -lm like you said I should, but I get this when I run it: $ ./a.out 2.1 ^ 6 = 1023.000000 This is not the right answer! What is going on? A. When the compiler sees you call a function, it checks if it has already seen a prototype for it. If it has not, it assumes the function returns an int, which is definitely not what you want here. Q. So how do I fix this? A. The prototypes for the mathematical functions are in math.h. If you include this file, the compiler will be able to find the prototype and it will stop doing strange things to your calculation! #include <math.h> #include <stdio.h> int main() { ... After recompiling it as you did before, run it: $ ./a.out 2.1 ^ 6 = 85.766121 If you are using any of the mathematical functions, always include math.h and remember to link in the math library. Q. I compiled a file called foobar.c and I cannot find an executable called foobar. Where's it gone? A. Remember, cc will call the executable a.out unless you tell it differently. Use the option: $ cc -o foobar foobar.c Q. OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it? A. Unlike MS-DOS, Unix does not look in the current directory when it is trying to find out which executable you want it to run, unless you tell it to. Either type ./foobar, which means run the file called foobar in the current directory, or change your PATH environment variable so that it looks something like bin:/usr/bin:/usr/local/bin:. The dot at the end means look in the current directory if it is not in any of the others. Q. I called my executable test, but nothing happens when I run it. What is going on? A. Most Unix systems have a program called test in /usr/bin and the shell is picking that one up before it gets to checking the current directory. Either type: $ ./test or choose a better name for your program! Q. I compiled my program and it seemed to run all right at first, then there was an error and it said something about core dumped. What does that mean? A. The name core dump dates back to the very early days of Unix, when the machines used core memory for storing data. Basically, if the program failed under certain conditions, the system would write the contents of core memory to disk in a file called core, which the programmer could then pore over to find out what went wrong. Q. Fascinating stuff, but what I am supposed to do now? A. Use gdb to analyse the core (see ). Q. When my program dumped core, it said something about a segmentation fault. What's that? A. This basically means that your program tried to perform some sort of illegal operation on memory; Unix is designed to protect the operating system and other programs from rogue programs. Common causes for this are: Trying to write to a NULL pointer, eg char *foo = NULL; strcpy(foo, "bang!"); Using a pointer that hasn't been initialised, eg char *foo; strcpy(foo, "bang!"); The pointer will have some random value that, with luck, will point into an area of memory that isn't available to your program and the kernel will kill your program before it can do any damage. If you're unlucky, it'll point somewhere inside your own program and corrupt one of your data structures, causing the program to fail mysteriously. Trying to access past the end of an array, eg int bar[20]; bar[27] = 6; Trying to store something in read-only memory, eg char *foo = "My string"; strcpy(foo, "bang!"); Unix compilers often put string literals like "My string" into read-only areas of memory. Doing naughty things with malloc() and free(), eg char bar[80]; free(bar); or char *foo = malloc(27); free(foo); free(foo); Making one of these mistakes will not always lead to an error, but they are always bad practice. Some systems and compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try them on an another. Q. Sometimes when I get a core dump it says bus error. It says in my Unix book that this means a hardware problem, but the computer still seems to be working. Is this true? A. No, fortunately not (unless of course you really do have a hardware problem…). This is usually another way of saying that you accessed memory in a way you shouldn't have. Q. This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. Can I do this, or do I have to wait until there's an error? A. Yes, just go to another console or xterm, do $ ps to find out the process ID of your program, and do $ kill -ABRT pid where pid is the process ID you looked up. This is useful if your program has got stuck in an infinite loop, for instance. If your program happens to trap SIGABRT, there are several other signals which have a similar effect. Make What is <command>make</command>? When you're working on a simple program with only one or two source files, typing in $ cc file1.c file2.c is not too bad, but it quickly becomes very tedious when there are several files—and it can take a while to compile, too. One way to get around this is to use object files and only recompile the source file if the source code has changed. So we could have something like: $ cc file1.o file2.ofile37.c &hellip if we'd changed file37.c, but not any of the others, since the last time we compiled. This may speed up the compilation quite a bit, but doesn't solve the typing problem. Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it very inefficient on a large project. What happens if we have hundreds of source files lying about? What if we're working in a team with other people who forget to tell us when they've changed one of their source files that we use? Perhaps we could put the two solutions together and write something like a shell script that would contain some kind of magic rule saying when a source file needs compiling. Now all we need now is a program that can understand these rules, as it's a bit too complicated for the shell. This program is called make. It reads in a file, called a makefile, that tells it how different files depend on each other, and works out which files need to be re-compiled and which ones don't. For example, a rule could say something like if fromboz.o is older than fromboz.c, that means someone must have changed fromboz.c, so it needs to be re-compiled. The makefile also has rules telling make how to re-compile the source file, making it a much more powerful tool. Makefiles are typically kept in the same directory as the source they apply to, and can be called makefile, Makefile or MAKEFILE. Most programmers use the name Makefile, as this puts it near the top of a directory listing, where it can easily be seen.They don't use the MAKEFILE form as block capitals are often used for documentation files like README. Example of using <command>make</command> Here's a very simple make file: foo: foo.c cc -o foo foo.c It consists of two lines, a dependency line and a creation line. The dependency line here consists of the name of the program (known as the target), followed by a colon, then whitespace, then the name of the source file. When make reads this line, it looks to see if foo exists; if it exists, it compares the time foo was last modified to the time foo.c was last modified. If foo does not exist, or is older than foo.c, it then looks at the creation line to find out what to do. In other words, this is the rule for working out when foo.c needs to be re-compiled. The creation line starts with a tab (press the tab key) and then the command you would type to create foo if you were doing it at a command prompt. If foo is out of date, or does not exist, make then executes this command to create it. In other words, this is the rule which tells make how to re-compile foo.c. So, when you type make, it will make sure that foo is up to date with respect to your latest changes to foo.c. This principle can be extended to Makefiles with hundreds of targets—in fact, on FreeBSD, it is possible to compile the entire operating system just by typing make world in the appropriate directory! Another useful property of makefiles is that the targets don't have to be programs. For instance, we could have a make file that looks like this: foo: foo.c cc -o foo foo.c install: cp foo /home/me We can tell make which target we want to make by typing: $ make target make will then only look at that target and ignore any others. For example, if we type make foo with the makefile above, make will ignore the install target. If we just type make on its own, make will always look at the first target and then stop without looking at any others. So if we typed make here, it will just go to the foo target, re-compile foo if necessary, and then stop without going on to the install target. Notice that the install target doesn't actually depend on anything! This means that the command on the following line is always executed when we try to make that target by typing make install. In this case, it will copy foo into the user's home directory. This is often used by application makefiles, so that the application can be installed in the correct directory when it has been correctly compiled. This is a slightly confusing subject to try and explain. If you don't quite understand how make works, the best thing to do is to write a simple program like hello world and a make file like the one above and experiment. Then progress to using more than one source file, or having the source file include a header file. The touch command is very useful here—it changes the date on a file without you having to edit it. FreeBSD Makefiles Makefiles can be rather complicated to write. Fortunately, BSD-based systems like FreeBSD come with some very powerful ones as part of the system. One very good example of this is the FreeBSD ports system. Here's the essential part of a typical ports Makefile: MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include <bsd.port.mk> Now, if we go to the directory for this port and type make, the following happens: A check is made to see if the source code for this port is already on the system. If it isn't, an FTP connection to the URL in MASTER_SITES is set up to download the source. The checksum for the source is calculated and compared it with one for a known, good, copy of the source. This is to make sure that the source was not corrupted while in transit. Any changes required to make the source work on FreeBSD are applied—this is known as patching. Any special configuration needed for the source is done. (Many Unix program distributions try to work out which version of Unix they are being compiled on and which optional Unix features are present—this is where they are given the information in the FreeBSD ports scenario). The source code for the program is compiled. In effect, we change to the directory where the source was unpacked and do make—the program's own make file has the necessary information to build the program. We now have a compiled version of the program. If we wish, we can test it now; when we feel confident about the program, we can type make install. This will cause the program and any supporting files it needs to be copied into the correct location; an entry is also made into a package database, so that the port can easily be uninstalled later if we change our mind about it. Now I think you'll agree that's rather impressive for a four line script! The secret lies in the last line, which tells make to look in the system makefile called bsd.port.mk. It's easy to overlook this line, but this is where all the clever stuff comes from—someone has written a makefile that tells make to do all the things above (plus a couple of other things I didn't mention, including handling any errors that may occur) and anyone can get access to that just by putting a single line in their own make file! If you want to have a look at these system makefiles, they're in /usr/share/mk, but it's probably best to wait until you've had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) More advanced uses of <command>make</command> Make is a very powerful tool, and can do much more than the simple example above shows. Unfortunately, there are several different versions of make, and they all differ considerably. The best way to learn what they can do is probably to read the documentation—hopefully this introduction will have given you a base from which you can do this. The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in /usr/share/doc/psd/12.make. To view it, do $ zmore paper.ascii.gz in that directory. Many applications in the ports use GNU make, which has a very good set of info pages. If you have installed any of these ports, GNU make will automatically have been installed as gmake. It's also available as a port and package in its own right. To view the info pages for GNU make, you will have to edit the dir file in the /usr/local/info directory to add an entry for it. This involves adding a line like * Make: (make). The GNU Make utility. to the file. Once you have done this, you can type info and then select make from the menu (or in Emacs, do C-h i). Debugging The Debugger The debugger that comes with FreeBSD is called gdb (GNU debugger). You start it up by typing $ gdb progname although most people prefer to run it inside Emacs. You can do this by: M-x gdb RET progname RET Using a debugger allows you to run the program under more controlled circumstances. Typically, you can step through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a certain point and then stop, and so on. You can even attach to a program that's already running, or load a core file to investigate why the program crashed. It's even possible to debug the kernel, though that's a little trickier than the user applications we'll be discussing in this section. gdb has quite good on-line help, as well as a set of info pages, so this section will concentrate on a few of the basic commands. Finally, if you find its text-based command-prompt style off-putting, there's a graphical front-end for it xxgdb +URL="../../ports/devel.html">xxgdb in the ports collection. This section is intended to be an introduction to using gdb and does not cover specialised topics such as debugging the kernel. Running a program in the debugger You'll need to have compiled the program with the option to get the most out of using gdb. It will work without, but you'll only see the name of the function you're in, instead of the source code. If you see a line like: … (no debugging symbols found) …when gdb starts up, you'll know that the program wasn't compiled with the option. At the gdb prompt, type break main. This will tell the debugger to skip over the preliminary set-up code in the program and start at the beginning of your code. Now type run to start the program—it will start at the beginning of the set-up code and then get stopped by the debugger when it calls main(). (If you've ever wondered where main() gets called from, now you know!). You can now step through the program, a line at a time, by pressing n. If you get to a function call, you can step into it by pressing s. Once you're in a function call, you can return from stepping into a function call by pressing f. You can also use up and down to take a quick look at the caller. Here's a simple example of how to spot a mistake in a program with gdb. This is our program (with a deliberate mistake): #include <stdio.h> int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } This program sets i to be 5 and passes it to a function bazz() which prints out the number we gave it. When we compile and run the program we get $ cc -g -o temp temp.c $ ./temp This is my program anint = 4231 That wasn't what we expected! Time to see what's going on!$ gdb temp GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) break main Skip the set-up code Breakpoint 1 at 0x160f: file temp.c, line 9. gdb puts breakpoint at main() (gdb) run Run as far as main() Starting program: /home/james/tmp/temp Program starts running Breakpoint 1, main () at temp.c:9 gdb stops at main() (gdb) n Go to next line This is my program Program prints out (gdb) s step into bazz() bazz (anint=4231) at temp.c:17 gdb displays stack frame (gdb) Hang on a minute! How did anint get to be 4231? Didn't we set it to be 5 in main()? Let's move up to main() and have a look. (gdb) up Move up call stack #1 0x1625 in main () at temp.c:11 gdb displays stack frame (gdb) p i Show us the value of i $1 = 4231 gdb displays 4231 Oh dear! Looking at the code, we forgot to initialise i. We meant to put … main() { int i; i = 5; printf("This is my program\n"); &hellip but we left the i=5; line out. As we didn't initialise i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be 4231. gdb displays the stack frame every time we go into or out of a function, even if we're using up and down to move around the call stack. This shows the name of the function and the values of its arguments, which helps us keep track of where we are and what's going on. (The stack is a storage area where the program stores information about the arguments passed to functions and where to go when it returns from a function call). Examining a core file A core file is basically a file which contains the complete state of the process when it crashed. In the good old days, programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called progname.core instead of just core, to make it clearer which program a core file belongs to. To examine a core file, start up gdb in the usual way. Instead of typing break or run, type (gdb) core progname.core If you're not in the same directory as the core file, you'll have to do dir /path/to/core/file first. You should see something like this: $ gdb a.out GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) core a.out.core Core was generated by `a.out'. Program terminated with signal 11, Segmentation fault. Cannot access memory at address 0x7020796d. #0 0x164a in bazz (anint=0x5) at temp.c:17 (gdb) In this case, the program was called a.out, so the core file is called a.out.core. We can see that the program crashed due to trying to access an area in memory that was not available to it in a function called bazz. Sometimes it's useful to be able to see how a function was called, as the problem could have occurred a long way up the call stack in a complex program. The bt command causes gdb to print out a back-trace of the call stack: (gdb) bt #0 0x164a in bazz (anint=0x5) at temp.c:17 #1 0xefbfd888 in end () #2 0x162c in main () at temp.c:11 (gdb)The end() function is called when a program crashes; in this case, the bazz() function was called from main(). Attaching to a running program One of the neatest features about gdb is that it can attach to a program that's already running. Of course, that assumes you have sufficient permissions to do so. A common problem is when you are stepping through a program that forks, and you want to trace the child, but the debugger will only let you trace the parent. What you do is start up another gdb, use ps to find the process ID for the child, and do(gdb) attach pid in gdb, and then debug as usual. That's all very well, you're probably thinking, but by the time I've done that, the child process will be over the hill and far away. Fear not, gentle reader, here's how to do it (courtesy of the gdb info pages): &hellip if ((pid = fork()) < 0) /* _Always_ check this */ error(); else if (pid == 0) { /* child */ int PauseMode = 1; while (PauseMode) sleep(10); /* Wait until someone attaches to us */ &hellip } else { /* parent */ &hellip Now all you have to do is attach to the child, set PauseMode to 0, and wait for the sleep() call to return! Using Emacs as a Development Environment Emacs Unfortunately, Unix systems don't come with the kind of everything-you-ever-wanted-and-lots-more-you-didn't-in-one-gigantic-package integrated development environments that other systems have.At least, not unless you pay out very large sums of money. However, it is possible to set up your own environment. It may not be as pretty, and it may not be quite as integrated, but you can set it up the way you want it. And it's free. And you have the source to it. The key to it all is Emacs. Now there are some people who loathe it, but many who love it. If you're one of the former, I'm afraid this section will hold little of interest to you. Also, you'll need a fair amount of memory to run it—I'd recommend 8MB in text mode and 16MB in X as the bare minimum to get reasonable performance. Emacs is basically a highly customisable editor—indeed, it has been customised to the point where it's more like an operating system than an editor! Many developers and sysadmins do in fact spend practically all their time working inside Emacs, leaving it only to log out. It's impossible even to summarise everything Emacs can do here, but here are some of the features of interest to developers: Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to start/end of block expression, etc, etc. Pull-down menus and online help. Language-dependent syntax highlighting and indentation. Completely customisable. You can compile and debug programs within Emacs. On a compilation error, you can jump to the offending line of source code. Friendly-ish front-end to the info program used for reading GNU hypertext documentation, including the documentation on Emacs itself. Friendly front-end to gdb, allowing you to look at the source code as you step through your program. You can read Usenet news and mail while your program is compiling. And doubtless many more that I've overlooked. Emacs can be installed on FreeBSD using the Emacs +URL="../../ports/editors.html">the Emacs port. Once it's installed, start it up and do C-h t to read an Emacs tutorial—that means hold down the control key, press h, let go of the control key, and then press t. (Alternatively, you can you use the mouse to select Emacs Tutorial from the Help menu). Although Emacs does have menus, it's well worth learning the key bindings, as it's much quicker when you're editing something to press a couple of keys than to try and find the mouse and then click on the right place. And, when you're talking to seasoned Emacs users, you'll find they often casually throw around expressions like M-x replace-s RET foo RET bar RET so it's useful to know what they mean. And in any case, Emacs has far too many useful functions for them to all fit on the menu bars. Fortunately, it's quite easy to pick up the key-bindings, as they're displayed next to the menu item. My advice is to use the menu item for, say, opening a file until you understand how it works and feel confident with it, then try doing C-x C-f. When you're happy with that, move on to another menu command. If you can't remember what a particular combination of keys does, select Describe Key from the Help menu and type it in—Emacs will tell you what it does. You can also use the Command Apropos menu item to find out all the commands which contain a particular word in them, with the key binding next to it. By the way, the expression above means hold down the Meta key, press x, release the Meta key, type replace-s (short for replace-string—another feature of Emacs is that you can abbreviate commands), press the return key, type foo (the string you want replaced), press the return key, type bar (the string you want to replace foo with) and press return again. Emacs will then do the search-and-replace operation you've just requested. If you're wondering what on earth the Meta key is, it's a special key that many Unix workstations have. Unfortunately, PC's don't have one, so it's usually the alt key (or if you're unlucky, the escape key). Oh, and to get out of Emacs, do C-x C-c (that means hold down the control key, press c, press x and release the control key). If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore the bit in the documentation where it says C-z is the usual way to leave Emacs—that leaves Emacs hanging around in the background, and is only really useful if you're on a system which doesn't have virtual terminals). Configuring Emacs Emacs does many wonderful things; some of them are built in, some of them need to be configured. Instead of using a proprietary macro language for configuration, Emacs uses a version of Lisp specially adapted for editors, known as Emacs Lisp. This can be quite useful if you want to go on and learn something like Common Lisp, as it's considerably smaller than Common Lisp (although still quite big!). The best way to learn Emacs Lisp is to download the Emacs Tutorial However, there's no need to actually know any Lisp to get started with configuring Emacs, as I've included a sample .emacs file, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it's already running; it will read the commands from the file and (hopefully) give you a useful basic setup. A sample <filename>.emacs</filename> file Unfortunately, there's far too much here to explain it in detail; however there are one or two points worth mentioning. Everything beginning with a ; is a comment and is ignored by Emacs. In the first line, the -*- Emacs-Lisp -*- is so that we can edit the .emacs file itself within Emacs and get all the fancy features for editing Emacs Lisp. Emacs usually tries to guess this based on the filename, and may not get it right for .emacs. The tab key is bound to an indentation function in some modes, so when you press the tab key, it will indent the current line of code. If you want to put a tab character in whatever you're writing, hold the control key down while you're pressing the tab key. This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by guessing the language from the filename. Emacs already has a pre-defined function called next-error. In a compilation output window, this allows you to move from one compilation error to the next by doing M-n; we define a complementary function, previous-error, that allows you to go to a previous error by doing M-p. The nicest feature of all is that C-c C-c will open up the source file in which the error occurred and jump to the appropriate line. We enable Emacs's ability to act as a server, so that if you're doing something outside Emacs and you want to edit a file, you can just type in $ emacsclient filename and then you can edit the file in your Emacs!Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit a file. A sample <filename>.emacs</filename> file ;; -*-Emacs-Lisp-*- ;; This file is designed to be re-evaled; use the variable first-time ;; to avoid any problems with this. (defvar first-time t "Flag signifying this is the first time that .emacs has been evaled") ;; Meta (global-set-key "\M- " 'set-mark-command) (global-set-key "\M-\C-h" 'backward-kill-word) (global-set-key "\M-\C-r" 'query-replace) (global-set-key "\M-r" 'replace-string) (global-set-key "\M-g" 'goto-line) (global-set-key "\M-h" 'help-command) ;; Function keys (global-set-key [f1] 'manual-entry) (global-set-key [f2] 'info) (global-set-key [f3] 'repeat-complex-command) (global-set-key [f4] 'advertised-undo) (global-set-key [f5] 'eval-current-buffer) (global-set-key [f6] 'buffer-menu) (global-set-key [f7] 'other-window) (global-set-key [f8] 'find-file) (global-set-key [f9] 'save-buffer) (global-set-key [f10] 'next-error) (global-set-key [f11] 'compile) (global-set-key [f12] 'grep) (global-set-key [C-f1] 'compile) (global-set-key [C-f2] 'grep) (global-set-key [C-f3] 'next-error) (global-set-key [C-f4] 'previous-error) (global-set-key [C-f5] 'display-faces) (global-set-key [C-f8] 'dired) (global-set-key [C-f10] 'kill-compilation) ;; Keypad bindings (global-set-key [up] "\C-p") (global-set-key [down] "\C-n") (global-set-key [left] "\C-b") (global-set-key [right] "\C-f") (global-set-key [home] "\C-a") (global-set-key [end] "\C-e") (global-set-key [prior] "\M-v") (global-set-key [next] "\C-v") (global-set-key [C-up] "\M-\C-b") (global-set-key [C-down] "\M-\C-f") (global-set-key [C-left] "\M-b") (global-set-key [C-right] "\M-f") (global-set-key [C-home] "\M-<") (global-set-key [C-end] "\M->") (global-set-key [C-prior] "\M-<") (global-set-key [C-next] "\M->") ;; Mouse (global-set-key [mouse-3] 'imenu) ;; Misc (global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab. (setq backup-by-copying-when-mismatch t) ;; Treat 'y' or <CR> as yes, 'n' as no. (fset 'yes-or-no-p 'y-or-n-p) (define-key query-replace-map [return] 'act) (define-key query-replace-map [?\C-m] 'act) ;; Load packages (require 'desktop) (require 'tar-mode) ;; Pretty diff mode (autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files-remote "ediff" "Intelligent Emacs interface to diff") (if first-time (setq auto-mode-alist (append '(("\\.cpp$" . c++-mode) ("\\.hpp$" . c++-mode) ("\\.lsp$" . lisp-mode) ("\\.scm$" . scheme-mode) ("\\.pl$" . perl-mode) ) auto-mode-alist))) ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") (defvar font-lock-mode-keyword-alist '((c++-c-mode . c-font-lock-keywords) (perl-mode . perl-font-lock-keywords)) "Associations between modes and keywords") (defun font-lock-auto-mode-select () "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list" (if (memq major-mode font-lock-auto-mode-list) (progn (font-lock-mode t)) ) ) (global-set-key [M-f1] 'font-lock-fontify-buffer) ;; New dabbrev stuff ;(require 'new-dabbrev) (setq dabbrev-always-check-other-buffers t) (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") (add-hook 'emacs-lisp-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'c-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'text-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) t) (set (make-local-variable 'dabbrev-case-replace) t))) ;; C++ and C mode... (defun my-c++-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c++-mode-map "\C-ce" 'c-comment-edit) (setq c++-auto-hungry-initial-state 'none) (setq c++-delete-function 'backward-delete-char) (setq c++-tab-always-indent t) (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c++-empty-arglist-indent 4)) (defun my-c-mode-hook () (setq tab-width 4) (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c-mode-map "\C-ce" 'c-comment-edit) (setq c-auto-hungry-initial-state 'none) (setq c-delete-function 'backward-delete-char) (setq c-tab-always-indent t) ;; BSD-ish indentation style (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c-brace-offset -4) (setq c-argdecl-indent 0) (setq c-label-offset -4)) ;; Perl mode (defun my-perl-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (setq perl-indent-level 4) (setq perl-continued-statement-offset 4)) ;; Scheme mode... (defun my-scheme-mode-hook () (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent)) ;; Emacs-Lisp mode... (defun my-lisp-mode-hook () (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key lisp-mode-map "\C-i" 'lisp-indent-line) (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp)) ;; Add all of the hooks... (add-hook 'c++-mode-hook 'my-c++-mode-hook) (add-hook 'c-mode-hook 'my-c-mode-hook) (add-hook 'scheme-mode-hook 'my-scheme-mode-hook) (add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'perl-mode-hook 'my-perl-mode-hook) ;; Complement to next-error (defun previous-error (n) "Visit previous compilation error message and corresponding source code." (interactive "p") (next-error (- n))) ;; Misc... (transient-mark-mode 1) (setq mark-even-if-inactive t) (setq visible-bell nil) (setq next-line-add-newlines nil) (setq compile-command "make") (setq suggest-key-bindings nil) (put 'eval-expression 'disabled nil) (put 'narrow-to-region 'disabled nil) (put 'set-goal-column 'disabled nil) ;; Elisp archive searching (autoload 'format-lisp-code-directory "lispdir" nil t) (autoload 'lisp-dir-apropos "lispdir" nil t) (autoload 'lisp-dir-retrieve "lispdir" nil t) (autoload 'lisp-dir-verify "lispdir" nil t) ;; Font lock mode (defun my-make-face (face colour &optional bold) "Create a face from a colour and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face colour) (if bold (make-face-bold face)) ) (if (eq window-system 'x) (progn (my-make-face 'blue "blue") (my-make-face 'red "red") (my-make-face 'green "dark green") (setq font-lock-comment-face 'blue) (setq font-lock-string-face 'bold) (setq font-lock-type-face 'bold) (setq font-lock-keyword-face 'bold) (setq font-lock-function-name-face 'red) (setq font-lock-doc-string-face 'green) (add-hook 'find-file-hooks 'font-lock-auto-mode-select) (setq baud-rate 1000000) (global-set-key "\C-cmm" 'menu-bar-mode) (global-set-key "\C-cms" 'scroll-bar-mode) (global-set-key [backspace] 'backward-delete-char) ; (global-set-key [delete] 'delete-char) (standard-display-european t) (load-library "iso-transl"))) ;; X11 or PC using direct screen writes (if window-system (progn ;; (global-set-key [M-f1] 'hilit-repaint-command) ;; (global-set-key [M-f2] [?\C-u M-f1]) (setq hilit-mode-enable-list '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode scheme-mode) hilit-auto-highlight nil hilit-auto-rehighlight 'visible hilit-inhibit-hooks nil hilit-inhibit-rebinding t) (require 'hilit19) (require 'paren)) (setq baud-rate 2400) ; For slow serial connections ) ;; TTY type terminal (if (and (not window-system) (not (equal system-type 'ms-dos))) (progn (if first-time (progn (keyboard-translate ?\C-h ?\C-?) (keyboard-translate ?\C-? ?\C-h))))) ;; Under UNIX (if (not (equal system-type 'ms-dos)) (progn (if first-time (server-start)))) ;; Add any face changes here (add-hook 'term-setup-hook 'my-term-setup-hook) (defun my-term-setup-hook () (if (eq window-system 'pc) (progn ;; (set-face-background 'default "red") ))) ;; Restore the "desktop" - do this as late as possible (if first-time (progn (desktop-load-default) (desktop-read))) ;; Indicate that this file has been read at least once (setq first-time nil) ;; No need to debug anything now (setq debug-on-error nil) ;; All done (message "All done, %s%s" (user-login-name) ".") Extending the Range of Languages Emacs Understands Now, this is all very well if you only want to program in the languages already catered for in the .emacs file (C, C++, Perl, Lisp and Scheme), but what happens if a new language called whizbang comes out, full of exciting features? The first thing to do is find out if whizbang comes with any files that tell Emacs about the language. These usually end in .el, short for Emacs Lisp. For example, if whizbang is a FreeBSD port, we can locate these files by doing $ find /usr/ports/lang/whizbang -name "*.el" -print and install them by copying them into the Emacs site Lisp directory. On FreeBSD 2.1.0-RELEASE, this is /usr/local/share/emacs/site-lisp. So for example, if the output from the find command was /usr/ports/lang/whizbang/work/misc/whizbang.el we would do $ cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp Next, we need to decide what extension whizbang source files have. Let's say for the sake of argument that they all end in .wiz. We need to add an entry to our .emacs file to make sure Emacs will be able to use the information in whizbang.el. Find the auto-mode-alist entry in .emacs and add a line for whizbang, such as: … ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) This means that Emacs will automatically go into whizbang-mode when you edit a file ending in .wiz. Just below this, you'll find the font-lock-auto-mode-list entry. Add whizbang-mode to it like so: ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") This means that Emacs will always enable font-lock-mode (ie syntax highlighting) when editing a .wiz file. And that's all that's needed. If there's anything else you want done automatically when you open up a .wiz file, you can add a whizbang-mode hook (see my-scheme-mode-hook for a simple example that adds auto-indent). Further Reading Brian Harvey and Matthew Wright Simply Scheme MIT 1994. ISBN 0-262-08226-8 Randall Schwartz Learning Perl O'Reilly 1993 ISBN 1-56592-042-2 Patrick Henry Winston and Berthold Klaus Paul Horn Lisp (3rd Edition) Addison-Wesley 1989 ISBN 0-201-08319-1 Brian W. Kernighan and Rob Pike The Unix Programming Environment Prentice-Hall 1984 ISBN 0-13-937681-X Brian W. Kernighan and Dennis M. Ritchie The C Programming Language (2nd Edition) Prentice-Hall 1988 ISBN 0-13-110362-8 Bjarne Stroustrup The C++ Programming Language Addison-Wesley 1991 ISBN 0-201-53992-6 W. Richard Stevens Advanced Programming in the Unix Environment Addison-Wesley 1992 ISBN 0-201-56317-7 W. Richard Stevens Unix Network Programming Prentice-Hall 1990 ISBN 0-13-949876-1
diff --git a/en_US.ISO_8859-1/articles/new-users/article.sgml b/en_US.ISO_8859-1/articles/new-users/article.sgml index 67568b5590..9c3baeb6b5 100644 --- a/en_US.ISO_8859-1/articles/new-users/article.sgml +++ b/en_US.ISO_8859-1/articles/new-users/article.sgml @@ -1,943 +1,943 @@ - + For People New to Both FreeBSD and Unix Annelise Anderson
andrsn@andrsn.stanford.edu
August 15, 1997 Congratulations on installing FreeBSD! This introduction is for people new to both FreeBSD and Un*x—so it starts with basics. It assumes you're using version 2.0.5 or later of FreeBSD as distributed by Walnut Creek or FreeBSD.ORG, your system (for now) has a single user (you)—and you're probably pretty good with DOS/Windows or OS/2.
Logging in and Getting Out Log in (when you see login:) as a user you created during installation or as root. (Your FreeBSD installation will already have an account for root; root can go anywhere and do anything, including deleting essential files, so be careful!) The symbols % and # in the following stand for the prompt (yours may be different), with % indicating an ordinary user and # indicating root. To log out (and get a new login: prompt) type # exit as often as necessary. Yes, press enter after commands, and remember that Unix is case-sensitive—exit, not EXIT. To shut down the machine type: # /sbin/shutdown -h now Or to reboot type # /sbin/shutdown -r now or # /sbin/reboot You can also reboot with CtrlAltDelete. Give it a little time to do its work. This is equivalent to /sbin/reboot in recent releases of FreeBSD, and is much, much better than hitting the reset button. You don't want to have to reinstall this thing, do you? Adding A User with Root Privileges If you didn't create any users when you installed the system and are thus logged in as root, you should probably create a user now with # adduser The first time you use adduser, it might ask for some defaults to save. You might want to make the default shell csh instead of sh, if it suggests sh as the default. Otherwise just press enter to accept each default. These defaults are saved in /etc/adduser.conf, an editable file. Suppose you create a user jack with full name Jack Benimble. Give jack a password if security (even kids around who might pound on the keyboard) is an issue. When it asks you if you want to invite jack into other groups, type wheel Login group is ``jack''. Invite jack into other groups: wheel This will make it possible to log in as jack and use the su command to become root. Then you won't get scolded any more for logging in as root. You can quit adduser any time by typing CtrlC, and at the end you'll have a chance to approve your new user or simply type n for no. You might want to create a second new user (jill?) so that when you edit jack's login files, you'll have a hot spare in case something goes wrong. Once you've done this, use exit to get back to a login prompt and log in as jack. In general, it's a good idea to do as much work as possible as an ordinary user who doesn't have the power—and risk—of root. If you already created a user and you want the user to be able to su to root, you can log in as root and edit the file /etc/group, adding jack to the first line (the group wheel). But first you need to practice vi, the text editor--or use the simpler text editor, ee, installed on recent version of FreeBSD. To delete a user, use the rmuser command. Looking Around Logged in as an ordinary user, look around and try out some commands that will access the sources of help and information within FreeBSD. Here are some commands and what they do: id Tells you who you are! pwd Shows you where you are—the current working directory. ls Lists the files in the current directory. ls Lists the files in the current directory with a * after executables, a / after directories, and an @ after symbolic links. ls Lists the files in long format—size, date, permissions. ls Lists hidden dot files with the others. If you're root, thedot files show up without the switch. cd Changes directories. cd .. backs up one level; note the space after cd. cd /usr/local goes there. cd ~ goes to the home directory of the person logged in—e.g., /usr/home/jack. Try cd /cdrom, and then ls, to find out if your CDROM is mounted and working. view filename Lets you look at a file (named filename without changing it. Try view /etc/fstab. :q to quit. cat filename Displays filename on screen. If it's too long and you can see only the end of it, press ScrollLock and use the up-arrow to move backward; you can use ScrollLock with man pages too. Press ScrollLock again to quit scrolling. You might want to try cat on some of the dot files in your home directory—cat .cshrc, cat .login, cat .profile. You'll notice aliases in .cshrc for some of the ls commands (they're very convenient). You can create other aliases by editing .cshrc. You can make these aliases available to all users on the system by putting them in the system-wide csh configuration file, /etc/csh.cshrc. Getting Help and Information Here are some useful sources of help. Text stands for something of your choice that you type in—usually a command or filename. apropos text Everything containing string text in the whatis database. man text The man page for text. The major source of documentation for Un*x systems. man ls will tell you all the ways to use the ls command. Press Enter to move through text, Ctrlb to go back a page, Ctrlf to go forward, q or Ctrlc to quit. which text Tells you where in the user's path the command text is found. locate text All the paths where the string text is found. whatis text Tells you what the command text does and its man page. Typing whatis * will tell you about all the binaries in the current directory. whereis text Finds the file text, giving its full path. You might want to try using whatis on some common useful commands like cat, more, grep, mv, find, tar, chmod, chown, date, and script. more lets you read a page at a time as it does in DOS, e.g., ls -l | more or more filename. The * works as a wildcard—e.g., ls w* will show you files beginning with w. Are some of these not working very well? Both locate and whatis depend on a database that's rebuilt weekly. If your machine isn't going to be left on over the weekend (and running FreeBSD), you might want to run the commands for daily, weekly, and monthly maintenance now and then. Run them as root and give each one time to finish before you start the next one, for now. # /etc/daily output omitted # /etc/weekly output omitted # /etc/monthly output omitted If you get tired waiting, press AltF2 to get another virtual console, and log in again. After all, it's a multi-user, multi-tasking system. Nevertheless these commands will probably flash messages on your screen while they're running; you can type clear at the prompt to clear the screen. Once they've run, you might want to look at /var/mail/root and /var/log/messages. Basically running such commands is part of system administration—and as a single user of a Unix system, you're your own system administrator. Virtually everything you need to be root to do is system administration. Such responsibilities aren't covered very well even in those big fat books on Unix, which seem to devote a lot of space to pulling down menus in windows managers. You might want to get one of the two leading books on systems administration, either Evi Nemeth et.al.'s UNIX System Administration Handbook (Prentice-Hall, 1995, ISBN 0-13-15051-7)—the second edition with the red cover; or Æleen Frisch's Essential System Administration (O'Reilly & Associates, 1993, ISBN 0-937175-80-3). I used Nemeth. Editing Text To configure your system, you need to edit text files. Most of them will be in the /etc directory; and you'll need to su to root to be able to change them. You can use the easy ee, but in the long run the text editor vi is worth learning. There's an excellent tutorial on vi in /usr/src/contrib/nvi/docs/tutorial if you have that installed; otherwise you can get it by ftp to ftp.cdrom.com in the directory FreeBSD/FreeBSD-current/src/contrib/nvi/docs/tutorial. Before you edit a file, you should probably back it up. Suppose you want to edit /etc/rc.conf. You could just use cd /etc to get to the /etc directory and do: # cp rc.conf rc.conf.orig This would copy rc.conf to rc.conf.orig, and you could later copy rc.conf.orig to rc.conf to recover the original. But even better would be moving (renaming) and then copying back: # mv rc.conf rc.conf.orig # cp rc.conf.orig rc.conf because the mv command preserves the original date and owner of the file. You can now edit rc.conf. If you want the original back, you'd then mv rc.conf rc.conf.myedit (assuming you want to preserve your edited version) and then # mv rc.conf.orig rc.conf to put things back the way they were. To edit a file, type # vi filename Move through the text with the arrow keys. Esc (the escape key) puts vi in command mode. Here are some commands: x delete letter the cursor is on dd delete the entire line (even if it wraps on the screen) i insert text at the cursor a insert text after the cursor Once you type i or a, you can enter text. Esc puts you back in command mode where you can type :w to write your changes to disk and continue editing :wq to write and quit :q! to quit without saving changes /text to move the cursor to text; /Enter (the enter key) to find the next instance of text. G to go to the end of the file nG to go to line n in the file, where n is a number CtrlL to redraw the screen Ctrlb and Ctrlf go back and forward a screen, as they do with more and view. Practice with vi in your home directory by creating a new file with vi filename and adding and deleting text, saving the file, and calling it up again. vi delivers some surprises because it's really quite complex, and sometimes you'll inadvertently issue a command that will do something you don't expect. (Some people actually like vi—it's more powerful than DOS EDIT—find out about the :r command.) Use Esc one or more times to be sure you're in command mode and proceed from there when it gives you trouble, save often with :w, and use :q! to get out and start over (from your last :w) when you need to. Now you can cd to /etc, su to root, use vi to edit the file /etc/group, and add a user to wheel so the user has root privileges. Just add a comma and the user's login name to the end of the first line in the file, press Esc, and use :wq to write the file to disk and quit. Instantly effective. (You didn't put a space after the comma, did you?) Printing Files from DOS At this point you probably don't have the printer working, so here's a way to create a file from a man page, move it to a floppy, and then print it from DOS. Suppose you want to read carefully about changing permissions on files (pretty important). You can use the command man chmod to read about it. The command # man chmod | col -b > chmod.txt will remove formatting codes and send the man page to the chmod.txt file instead of showing it on your screen. Now put a dos-formatted diskette in your floppy drive a, su to root, and type # /sbin/mount -t msdos /dev/fd0 /mnt to mount the floppy drive on /mnt. Now (you no longer need to be root, and you can type exit to get back to being user jack) you can go to the directory where you created chmod.txt and copy the file to the floppy with: % cp chmod.txt /mnt and use ls /mnt to get a directory listing of /mnt, which should show the file chmod.txt. You might especially want to make a file from /sbin/dmesg by typing % /sbin/dmesg > dmesg.txt and copying dmesg.txt to the floppy. /sbin/dmesg is the boot log record, and it's useful to understand it because it shows what FreeBSD found when it booted up. If you ask questions on freebsd-questions@FreeBSD.ORG or on a USENET group—like FreeBSD isn't finding my tape drive, what do I do?—people will want to know what dmesg has to say. You can now dismount the floppy drive (as root) to get the disk out with # /sbin/umount /mnt and reboot to go to DOS. Copy these files to a DOS directory, call them up with DOS EDIT, Windows Notepad or Wordpad, or a word processor, make a minor change so the file has to be saved, and print as you normally would from DOS or Windows. Hope it works! man pages come out best if printed with the dos print command. (Copying files from FreeBSD to a mounted dos partition is in some cases still a little risky.) Getting the printer printing from FreeBSD involves creating an appropriate entry in /etc/printcap and creating a matching spool directory in /var/spool/output. If your printer is on lpt0 (what dos calls LPT1), you may only need to go to /var/spool/output and (as root) create the directory lpd by typing: mkdir lpd, if it doesn't already exist. Then the printer should respond if it's turned on when the system is booted, and lp or lpr should send a file to the printer. Whether or not the file actually prints depends on configuring it, which is covered in the FreeBSD +URL="../../handbook/handbook.html">FreeBSD handbook. Other Useful Commands df shows file space and mounted systems. ps aux shows processes running. ps ax is a narrower form. rm filename remove filename. rm -R dir removes a directory dir and all subdirectories—careful! ls -R lists files in the current directory and all subdirectories; I used a variant, ls -AFR > where.txt, to get a list of all the files in / and (separately) /usr before I found better ways to find files. passwd to change user's password (or root's password) man hier man page on the Unix file system Use find to locate filename in /usr or any of its subdirectories with % find /usr -name "filename" You can use * as a wildcard in "filename" (which should be in quotes). If you tell find to search in / instead of /usr it will look for the file(s) on all mounted file systems, including the CDROM and the dos partition. An excellent book that explains Unix commands and utilities is Abrahams & Larson, Unix for the Impatient (2nd ed., Addison-Wesley, 1996). There's also a lot of Unix information on the Internet. Try the Unix Reference Desk. Next Steps You should now have the tools you need to get around and edit files, so you can get everything up and running. There is a great deal of information in the FreeBSD handbook (which is probably on your hard drive) and FreeBSD's web site. A wide variety of packages and ports are on the Walnut Creek CDROM as well as the web site. The handbook tells you more about how to use them (get the package if it exists, with pkg_add /cdrom/packages/All/packagename, where packagename is the filename of the package). The cdrom has lists of the packages and ports with brief descriptions in cdrom/packages/index, cdrom/packages/index.txt, and cdrom/ports/index, with fuller descriptions in /cdrom/ports/*/*/pkg/DESCR, where the *s represent subdirectories of kinds of programs and program names respectively. If you find the handbook too sophisticated (what with lndir and all) on installing ports from the cdrom, here's what usually works: Find the port you want, say kermit. There will be a directory for it on the cdrom. Copy the subdirectory to /usr/local (a good place for software you add that should be available to all users) with: # cp -R /cdrom/ports/comm/kermit /usr/local This should result in a /usr/local/kermit subdirectory that has all the files that the kermit subdirectory on the CDROM has. Next, create the directory /usr/ports/distfiles if it doesn't already exist using mkdir. Now check check /cdrom/ports/distfiles for a file with a name that indicates it's the port you want. Copy that file to /usr/ports/distfiles; in recent versions you can skip this step, as FreeBSD will do it for you. In the case of kermit, there is no distfile. Then cd to the subdirectory of /usr/local/kermit that has the file Makefile. Type # make all install During this process the port will ftp to get any compressed files it needs that it didn't find on the cdrom or in /usr/ports/distfiles. If you don't have your network running yet and there was no file for the port in /cdrom/ports/distfiles, you will have to get the distfile using another machine and copy it to /usr/ports/distfiles from a floppy or your dos partition. Read Makefile (with cat or more or view) to find out where to go (the master distribution site) to get the file and what its name is. Its name will be truncated when downloaded to DOS, and after you get it into /usr/ports/distfiles you'll have to rename it (with the mv command) to its original name so it can be found. (Use binary file transfers!) Then go back to /usr/local/kermit, find the directory with Makefile, and type make all install. The other thing that happens when installing ports or packages is that some other program is needed. If the installation stops with a message can't find unzip or whatever, you might need to install the package or port for unzip before you continue. Once it's installed type rehash to make FreeBSD reread the files in the path so it knows what's there. (If you get a lot of path not found messages when you use whereis or which, you might want to make additions to the list of directories in the path statement in .cshrc in your home directory. The path statement in Unix does the same kind of work it does in DOS, except the current directory is not (by default) in the path for security reasons; if the command you want is in the directory you're in, you need to type ./ before the command to make it work; no space after the slash.) You might want to get the most recent version of Netscape from their ftp site. (Netscape requires the X Window System.) There's now a FreeBSD version, so look around carefully. Just use gunzip filename and tar xvf filename on it, move the binary to /usr/local/bin or some other place binaries are kept, rehash, and then put the following lines in .cshrc in each user's home directory or (easier) in /etc/csh.cshrc, the system-wide csh start-up file: setenv XKEYSYMDB /usr/X11R6/lib/X11/XKeysymDB setenv XNLSPATH /usr/X11R6/lib/X11/nls This assumes that the file XKeysymDB and the directory nls are in /usr/X11R6/lib/X11; if they're not, find them and put them there. If you originally got Netscape as a port using the CDROM (or ftp), don't replace /usr/local/bin/netscape with the new netscape binary; this is just a shell script that sets up the environmental variables for you. Instead rename the new binary to netscape.bin and replace the old binary, which is /usr/local/lib/netscape/netscape.bin. Your Working Environment Your shell is the most important part of your working environment. In DOS, the usual shell is command.com. The shell is what interprets the commands you type on the command line, and thus communicates with the rest of the operating system. You can also write shell scripts, which are like DOS batch files: a series of commands to be run without your intervention. Two shells come installed with FreeBSD: csh and sh. csh is good for command-line work, but scripts should be written with sh (or bash). You can find out what shell you have by typing echo $SHELL. The csh shell is okay, but tcsh does everything csh does and more. It It allows you to recall commands with the arrow keys and edit them. It has tab-key completion of filenames (csh uses the escape key), and it lets you switch to the directory you were last in with cd -. It's also much easier to alter your prompt with tcsh. It makes life a lot easier. Here are the three steps for installing a new shell: 1. Install the shell as a port or a package, just as you would any other port or package. Use rehash and which tcsh (assuming you're installing tcsh) to make sure it got installed. 2. As root, edit /etc/shells, adding a line in the file for the new shell, in this case /usr/local/bin/tcsh, and save the file. (Some ports may do this for you.) 3. Use the chsh command to change your shell to tcsh permanently, or type tcsh at the prompt to change your shell without logging in again. Note: It can be dangerous to change root's shell to something other than sh or csh on early versions of FreeBSD and many other versions of Unix; you may not have a working shell when the system puts you into single user mode. The solution is to use su -m to become root, which will give you the tcsh as root, because the shell is part of the environment. You can make this permanent by adding it to your .tcshrc file as an alias with alias su su -m. When tcsh starts up, it will read the /etc/csh.cshrc and /etc/csh.login files, as does csh. It will also read the .login file in your home directory and the .cshrc file as well, unless you provide a .tcshrc file. This you can do by simply copying .cshrc to .tcshrc. Now that you've installed tcsh, you can adjust your prompt. You can find the details in the manual page for tcsh, but here is a line to put in your .tcshrc that will tell you how many commands you have typed, what time it is, and what directory you are in. It also produces a > if you're an ordinary user and a # if you're root, but tsch will do that in any case: set prompt = "%h %t %~ %# " This should go in the same place as the existing set prompt line if there is one, or under "if($?prompt) then" if not. Comment out the old line; you can always switch back to it if you prefer it. Don't forget the spaces and quotes. You can get the .tcshrc reread by typing source .tcshrc. You can get a listing of other environmental variables that have been set by typing env at the prompt. The result will show you your default editor, pager, and terminal type, among possibly many others. A useful command if you log in from a remote location and can't run a program because the terminal isn't capable is setenv TERM vt100. Other As root, you can dismount the CDROM with /sbin/umount /cdrom, take it out of the drive, insert another one, and mount it with /sbin/mount_cd9660 /dev/cd0a /cdrom assuming cd0a is the device name for your CDROM drive. The most recent versions of FreeBSD let you mount the cdrom with just /sbin/mount /cdrom. Using the live file system—the second of FreeBSD's CDROM disks—is useful if you've got limited space. What is on the live file system varies from release to release. You might try playing games from the cdrom. This involves using lndir, which gets installed with the X Window System, to tell the program(s) where to find the necessary files, because they're in the /cdrom file system instead of in /usr and its subdirectories, which is where they're expected to be. Read man lndir. Comments Welcome If you use this guide I'd be interested in knowing where it was unclear and what was left out that you think should be included, and if it was helpful. My thanks to Eugene W. Stark, professor of computer science at SUNY-Stony Brook, and John Fieber for helpful comments. Annelise Anderson, andrsn@andrsn.stanford.edu
diff --git a/en_US.ISO_8859-1/articles/programming-tools/article.sgml b/en_US.ISO_8859-1/articles/programming-tools/article.sgml index addd185ee8..65e1f87d26 100644 --- a/en_US.ISO_8859-1/articles/programming-tools/article.sgml +++ b/en_US.ISO_8859-1/articles/programming-tools/article.sgml @@ -1,1835 +1,1835 @@ - + A User's Guide to FreeBSD Programming Tools James Raynard
jraynard@freebsd.org
August 17, 1997 1997 James Raynard This document is an introduction to using some of the programming tools supplied with FreeBSD, although much of it will be applicable to many other versions of Unix. It does not attempt to describe coding in any detail. Most of the document assumes little or no previous programming knowledge, although it is hoped that most programmers will find something of value in it
Introduction<anchor id=foo> FreeBSD offers an excellent development environment. Compilers for C, C++, and Fortran and an assembler come with the basic system, not to mention a Perl interpreter and classic Unix tools such as sed and awk. If that is not enough, there are many more compilers and interpreters in the Ports collection. FreeBSD is very compatible with standards such as POSIX and ANSI C, as well with its own BSD heritage, so it is possible to write applications that will compile and run with little or no modification on a wide range of platforms. However, all this power can be rather overwhelming at first if you've never written programs on a Unix platform before. This document aims to help you get up and running, without getting too deeply into more advanced topics. The intention is that this document should give you enough of the basics to be able to make some sense of the documentation. Most of the document requires little or no knowledge of programming, although it does assume a basic competence with using Unix and a willingness to learn! Introduction to Programming A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to perform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can give these instructions, or commands as they are usually called. One way uses an interpreter, the other a compiler. As human languages are too difficult for a computer to understand in an unambiguous way, commands are usually written in one or other languages specially designed for the purpose. Interpreters With an interpreter, the language comes as an environment, where you type in commands at a prompt and the environment executes them for you. For more complicated programs, you can type the commands into a file and get the interpreter to load the file and execute the commands in it. If anything goes wrong, many interpreters will drop you into a debugger to help you track down the problem. The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected readily. The biggest disadvantage comes when you want to share your programs with someone. They must have the same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. Also users may not appreciate being thrown into a debugger if they press the wrong key! From a performance point of view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers. In my opinion, interpreted languages are the best way to start if you have not done any programming before. This kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also be argued that the Unix shell (sh, csh) is itself an interpreter, and many people do in fact write shell scripts to help with various housekeeping tasks on their machine. Indeed, part of the original Unix philosophy was to provide lots of small utility programs that could be linked together in shell scripts to perform useful tasks. Interpreters available with FreeBSD Here is a list of interpreters that are available as FreeBSD packages, with a brief discussion of some of the more popular interpreted languages. To get one of these packages, all you need to do is to click on the hotlink for the package, then run $ pkg_add package name as root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later system for the package to work! BASIC Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching University students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been the first programming language for many programmers. It's also the foundation for Visual Basic. The Bywater Basic Interpreter and the Phil Cockroft's Basic Interpreter (formerly Rabbit Basic) are available as FreeBSD FreeBSD packages Lisp A language that was developed in the late 1950s as an alternative to the number-crunching languages that were popular at the time. Instead of being based on numbers, Lisp is based on lists; in fact the name is short for List Processing. Very popular in AI (Artificial Intelligence) circles. Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. FreeBSD has GNU Common Lisp available as a package. Perl Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. Version 4, which is probably still the most widely-used version, comes with FreeBSD; the newer Perl Version 5 is available as a package. Scheme A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it is simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to be used in research work. FreeBSD has packages of the Elk Scheme Interpreter, the MIT Scheme Interpreter and the SCM Scheme Interpreter. Icon The Icon Programming Language. Logo Brian Harvey's LOGO Interpreter. Python The Python Object-Oriented Programming Language Compilers Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then run the compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the editor; if it did compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works properly.If you run it in the shell, you may get a core dump. Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things which are very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating system—or even writing your own operating system! It's also useful if you need to write very efficient code, as the compiler can take its time and optimise the code, which would not be acceptable in an interpreter. And distributing a program written for a compiler is usually more straightforward than one written for an interpreter—you can just give them a copy of the executable, assuming they have the same operating system as you. Compiled languages include Pascal, C and C++. C and C++ are rather unforgiving languages, and best suited to more experienced programmers; Pascal, on the other hand, was designed as an educational language, and is quite a good language to start with. Unfortunately, FreeBSD doesn't have any Pascal support, except for a Pascal-to-C converter in the ports. As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not have an IDE as such; however it is possible to use Emacs for this purpose. This is discussed in . Compiling with <command>cc</command> This section deals only with the GNU compiler for C and C++, since that comes with the base FreeBSD system. It can be invoked by either cc or gcc. The details of producing a program with an interpreter vary considerably between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. Once you've written your masterpiece, the next step is to convert it into something that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which is done by a separate program. Pre-process your source code to remove comments and do other tricks like expanding macros in C. Check the syntax of your code to see if you have obeyed the rules of the language. If you have not, it will complain! Convert the source code into assembly language—this is very close to machine code, but still understandable by humans. Allegedly.To be strictly accurate, cc converts the source code into its own, machine-independent p-code instead of assembly language at this stage. Convert the assembly language into machine code—yep, we are talking bits and bytes, ones and zeros here. Check that you have used things like functions and global variables in a consistent way. For example, if you have called a non-existent function, it will complain. If you are trying to produce an executable from several source code files, work out how to fit them all together. Work out how to produce something that the system's run-time loader will be able to load into memory and run. Finally, write the executable on the file system. The word compiling is often used to refer to just steps 1 to 4—the others are referred to as linking. Sometimes step 1 is referred to as pre-processing and steps 3-4 as assembling. Fortunately, almost all this detail is hidden from you, as cc is a front end that manages calling all these programs with the right arguments for you; simply typing $ cc foobar.c will cause foobar.c to be compiled by all the steps above. If you have more than one file to compile, just do something like $ cc foo.c bar.c Note that the syntax checking is just that—checking the syntax. It will not check for any logical mistakes you may have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort.In case you didn't know, a binary sort is an efficient way of sorting things into order and a bubble sort isn't. There are lots and lots of options for cc, which are all in the man page. Here are a few of the most important ones, with examples of how to use them. The output name of the file. If you do not use this option, cc will produce an executable called a.out.The reasons for this are buried in the mists of history. $ cc foobar.c executable is a.out $ cc -o foobar foobar.c executable is foobar Just compile the file, do not link it. Useful for toy programs where you just want to check the syntax, or if you are using a Makefile. $ cc -c foobar.c This will produce an object file (not an executable) called foobar.o. This can be linked together with other object files into an executable. Create a debug version of the executable. This makes the compiler put information into the executable about which line of which source file corresponds to which function call. A debugger can use this information to show the source code as you step through the program, which is very useful; the disadvantage is that all this extra information makes the program much bigger. Normally, you compile with while you are developing a program and then compile a release version without when you're satisfied it works properly. $ cc -g foobar.c This will produce a debug version of the program.Note, we didn't use the flag to specify the executable name, so we will get an executable called a.out. Producing a debug version called foobar is left as an exercise for the reader! Create an optimised version of the executable. The compiler performs various clever tricks to try and produce an executable that runs faster than normal. You can add a number after the to specify a higher level of optimisation, but this often exposes bugs in the compiler's optimiser. For instance, the version of cc that comes with the 2.1.0 release of FreeBSD is known to produce bad code with the option in some circumstances. Optimisation is usually only turned on when compiling a release version. $ cc -O -o foobar foobar.c This will produce an optimised version of foobar. The following three flags will force cc to check that your code complies to the relevant international standard, often referred to as the ANSI standard, though strictly speaking it is an ISO standard. Enable all the warnings which the authors of cc believe are worthwhile. Despite the name, it will not enable all the warnings cc is capable of. Turn off most, but not all, of the non-ANSI C features provided by cc. Despite the name, it does not guarantee strictly that your code will comply to the standard. Turn off all cc's non-ANSI C features. Without these flags, cc will allow you to use some of its non-standard extensions to the standard. Some of these are very useful, but will not work with other compilers—in fact, one of the main aims of the standard is to allow people to write code that will work with any compiler on any system. This is known as portable code. Generally, you should try to make your code as portable as possible, as otherwise you may have to completely re-write the program later to get it to work somewhere else—and who knows what you may be using in a few years time? $ cc -Wall -ansi -pedantic -o foobar foobar.c This will produce an executable foobar after checking foobar.c for standard compliance. Specify a function library to be used during when linking. The most common example of this is when compiling a program that uses some of the mathematical functions in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell the compiler to add it. The rule is that if the library is called libsomething.a, you give cc the argument . For example, the math library is libm.a, so you give cc the argument . A common gotcha with the math library is that it has to be the last library on the command line. $ cc -o foobar foobar.c -lm This will link the math library functions into foobar. If you are compiling C++ code, you need to add , or if you are using FreeBSD 2.2 or later, to the command line argument to link the C++ library functions. Alternatively, you can run c++ instead of cc, which does this for you. c++ can also be invoked as g++ on FreeBSD. $ cc -o foobar foobar.cc -lg++ For FreeBSD 2.1.6 and earlier $ cc -o foobar foobar.cc -lstdc++ For FreeBSD 2.2 and later $ c++ -o foobar foobar.cc Each of these will both produce an executable foobar from the C++ source file foobar.cc. Note that, on Unix systems, C++ source files traditionally end in .C, .cxx or .cc, rather than the MS-DOS style .cpp (which was already used for something else). gcc used to rely on this to work out what kind of compiler to use on the source file; however, this restriction no longer applies, so you may now call your C++ files .cpp with impunity! Common <command>cc</command> Queries and Problems Q. I am trying to write a program which uses the sin() function and I get an error like this. What does it mean? /var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment A. When using mathematical functions like sin(), you have to tell cc to link in the math library, like so: $ cc -o foobar foobar.c -lm Q. All right, I wrote this simple program to practice using . All it does is raise 2.1 to the power of 6. #include <stdio.h> int main() { float f; f = pow(2.1, 6); printf("2.1 ^ 6 = %f\n", f); return 0; } and I compiled it as: $ cc temp.c -lm like you said I should, but I get this when I run it: $ ./a.out 2.1 ^ 6 = 1023.000000 This is not the right answer! What is going on? A. When the compiler sees you call a function, it checks if it has already seen a prototype for it. If it has not, it assumes the function returns an int, which is definitely not what you want here. Q. So how do I fix this? A. The prototypes for the mathematical functions are in math.h. If you include this file, the compiler will be able to find the prototype and it will stop doing strange things to your calculation! #include <math.h> #include <stdio.h> int main() { ... After recompiling it as you did before, run it: $ ./a.out 2.1 ^ 6 = 85.766121 If you are using any of the mathematical functions, always include math.h and remember to link in the math library. Q. I compiled a file called foobar.c and I cannot find an executable called foobar. Where's it gone? A. Remember, cc will call the executable a.out unless you tell it differently. Use the option: $ cc -o foobar foobar.c Q. OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it? A. Unlike MS-DOS, Unix does not look in the current directory when it is trying to find out which executable you want it to run, unless you tell it to. Either type ./foobar, which means run the file called foobar in the current directory, or change your PATH environment variable so that it looks something like bin:/usr/bin:/usr/local/bin:. The dot at the end means look in the current directory if it is not in any of the others. Q. I called my executable test, but nothing happens when I run it. What is going on? A. Most Unix systems have a program called test in /usr/bin and the shell is picking that one up before it gets to checking the current directory. Either type: $ ./test or choose a better name for your program! Q. I compiled my program and it seemed to run all right at first, then there was an error and it said something about core dumped. What does that mean? A. The name core dump dates back to the very early days of Unix, when the machines used core memory for storing data. Basically, if the program failed under certain conditions, the system would write the contents of core memory to disk in a file called core, which the programmer could then pore over to find out what went wrong. Q. Fascinating stuff, but what I am supposed to do now? A. Use gdb to analyse the core (see ). Q. When my program dumped core, it said something about a segmentation fault. What's that? A. This basically means that your program tried to perform some sort of illegal operation on memory; Unix is designed to protect the operating system and other programs from rogue programs. Common causes for this are: Trying to write to a NULL pointer, eg char *foo = NULL; strcpy(foo, "bang!"); Using a pointer that hasn't been initialised, eg char *foo; strcpy(foo, "bang!"); The pointer will have some random value that, with luck, will point into an area of memory that isn't available to your program and the kernel will kill your program before it can do any damage. If you're unlucky, it'll point somewhere inside your own program and corrupt one of your data structures, causing the program to fail mysteriously. Trying to access past the end of an array, eg int bar[20]; bar[27] = 6; Trying to store something in read-only memory, eg char *foo = "My string"; strcpy(foo, "bang!"); Unix compilers often put string literals like "My string" into read-only areas of memory. Doing naughty things with malloc() and free(), eg char bar[80]; free(bar); or char *foo = malloc(27); free(foo); free(foo); Making one of these mistakes will not always lead to an error, but they are always bad practice. Some systems and compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try them on an another. Q. Sometimes when I get a core dump it says bus error. It says in my Unix book that this means a hardware problem, but the computer still seems to be working. Is this true? A. No, fortunately not (unless of course you really do have a hardware problem…). This is usually another way of saying that you accessed memory in a way you shouldn't have. Q. This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. Can I do this, or do I have to wait until there's an error? A. Yes, just go to another console or xterm, do $ ps to find out the process ID of your program, and do $ kill -ABRT pid where pid is the process ID you looked up. This is useful if your program has got stuck in an infinite loop, for instance. If your program happens to trap SIGABRT, there are several other signals which have a similar effect. Make What is <command>make</command>? When you're working on a simple program with only one or two source files, typing in $ cc file1.c file2.c is not too bad, but it quickly becomes very tedious when there are several files—and it can take a while to compile, too. One way to get around this is to use object files and only recompile the source file if the source code has changed. So we could have something like: $ cc file1.o file2.ofile37.c &hellip if we'd changed file37.c, but not any of the others, since the last time we compiled. This may speed up the compilation quite a bit, but doesn't solve the typing problem. Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it very inefficient on a large project. What happens if we have hundreds of source files lying about? What if we're working in a team with other people who forget to tell us when they've changed one of their source files that we use? Perhaps we could put the two solutions together and write something like a shell script that would contain some kind of magic rule saying when a source file needs compiling. Now all we need now is a program that can understand these rules, as it's a bit too complicated for the shell. This program is called make. It reads in a file, called a makefile, that tells it how different files depend on each other, and works out which files need to be re-compiled and which ones don't. For example, a rule could say something like if fromboz.o is older than fromboz.c, that means someone must have changed fromboz.c, so it needs to be re-compiled. The makefile also has rules telling make how to re-compile the source file, making it a much more powerful tool. Makefiles are typically kept in the same directory as the source they apply to, and can be called makefile, Makefile or MAKEFILE. Most programmers use the name Makefile, as this puts it near the top of a directory listing, where it can easily be seen.They don't use the MAKEFILE form as block capitals are often used for documentation files like README. Example of using <command>make</command> Here's a very simple make file: foo: foo.c cc -o foo foo.c It consists of two lines, a dependency line and a creation line. The dependency line here consists of the name of the program (known as the target), followed by a colon, then whitespace, then the name of the source file. When make reads this line, it looks to see if foo exists; if it exists, it compares the time foo was last modified to the time foo.c was last modified. If foo does not exist, or is older than foo.c, it then looks at the creation line to find out what to do. In other words, this is the rule for working out when foo.c needs to be re-compiled. The creation line starts with a tab (press the tab key) and then the command you would type to create foo if you were doing it at a command prompt. If foo is out of date, or does not exist, make then executes this command to create it. In other words, this is the rule which tells make how to re-compile foo.c. So, when you type make, it will make sure that foo is up to date with respect to your latest changes to foo.c. This principle can be extended to Makefiles with hundreds of targets—in fact, on FreeBSD, it is possible to compile the entire operating system just by typing make world in the appropriate directory! Another useful property of makefiles is that the targets don't have to be programs. For instance, we could have a make file that looks like this: foo: foo.c cc -o foo foo.c install: cp foo /home/me We can tell make which target we want to make by typing: $ make target make will then only look at that target and ignore any others. For example, if we type make foo with the makefile above, make will ignore the install target. If we just type make on its own, make will always look at the first target and then stop without looking at any others. So if we typed make here, it will just go to the foo target, re-compile foo if necessary, and then stop without going on to the install target. Notice that the install target doesn't actually depend on anything! This means that the command on the following line is always executed when we try to make that target by typing make install. In this case, it will copy foo into the user's home directory. This is often used by application makefiles, so that the application can be installed in the correct directory when it has been correctly compiled. This is a slightly confusing subject to try and explain. If you don't quite understand how make works, the best thing to do is to write a simple program like hello world and a make file like the one above and experiment. Then progress to using more than one source file, or having the source file include a header file. The touch command is very useful here—it changes the date on a file without you having to edit it. FreeBSD Makefiles Makefiles can be rather complicated to write. Fortunately, BSD-based systems like FreeBSD come with some very powerful ones as part of the system. One very good example of this is the FreeBSD ports system. Here's the essential part of a typical ports Makefile: MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include <bsd.port.mk> Now, if we go to the directory for this port and type make, the following happens: A check is made to see if the source code for this port is already on the system. If it isn't, an FTP connection to the URL in MASTER_SITES is set up to download the source. The checksum for the source is calculated and compared it with one for a known, good, copy of the source. This is to make sure that the source was not corrupted while in transit. Any changes required to make the source work on FreeBSD are applied—this is known as patching. Any special configuration needed for the source is done. (Many Unix program distributions try to work out which version of Unix they are being compiled on and which optional Unix features are present—this is where they are given the information in the FreeBSD ports scenario). The source code for the program is compiled. In effect, we change to the directory where the source was unpacked and do make—the program's own make file has the necessary information to build the program. We now have a compiled version of the program. If we wish, we can test it now; when we feel confident about the program, we can type make install. This will cause the program and any supporting files it needs to be copied into the correct location; an entry is also made into a package database, so that the port can easily be uninstalled later if we change our mind about it. Now I think you'll agree that's rather impressive for a four line script! The secret lies in the last line, which tells make to look in the system makefile called bsd.port.mk. It's easy to overlook this line, but this is where all the clever stuff comes from—someone has written a makefile that tells make to do all the things above (plus a couple of other things I didn't mention, including handling any errors that may occur) and anyone can get access to that just by putting a single line in their own make file! If you want to have a look at these system makefiles, they're in /usr/share/mk, but it's probably best to wait until you've had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) More advanced uses of <command>make</command> Make is a very powerful tool, and can do much more than the simple example above shows. Unfortunately, there are several different versions of make, and they all differ considerably. The best way to learn what they can do is probably to read the documentation—hopefully this introduction will have given you a base from which you can do this. The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in /usr/share/doc/psd/12.make. To view it, do $ zmore paper.ascii.gz in that directory. Many applications in the ports use GNU make, which has a very good set of info pages. If you have installed any of these ports, GNU make will automatically have been installed as gmake. It's also available as a port and package in its own right. To view the info pages for GNU make, you will have to edit the dir file in the /usr/local/info directory to add an entry for it. This involves adding a line like * Make: (make). The GNU Make utility. to the file. Once you have done this, you can type info and then select make from the menu (or in Emacs, do C-h i). Debugging The Debugger The debugger that comes with FreeBSD is called gdb (GNU debugger). You start it up by typing $ gdb progname although most people prefer to run it inside Emacs. You can do this by: M-x gdb RET progname RET Using a debugger allows you to run the program under more controlled circumstances. Typically, you can step through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a certain point and then stop, and so on. You can even attach to a program that's already running, or load a core file to investigate why the program crashed. It's even possible to debug the kernel, though that's a little trickier than the user applications we'll be discussing in this section. gdb has quite good on-line help, as well as a set of info pages, so this section will concentrate on a few of the basic commands. Finally, if you find its text-based command-prompt style off-putting, there's a graphical front-end for it xxgdb +URL="../../ports/devel.html">xxgdb in the ports collection. This section is intended to be an introduction to using gdb and does not cover specialised topics such as debugging the kernel. Running a program in the debugger You'll need to have compiled the program with the option to get the most out of using gdb. It will work without, but you'll only see the name of the function you're in, instead of the source code. If you see a line like: … (no debugging symbols found) …when gdb starts up, you'll know that the program wasn't compiled with the option. At the gdb prompt, type break main. This will tell the debugger to skip over the preliminary set-up code in the program and start at the beginning of your code. Now type run to start the program—it will start at the beginning of the set-up code and then get stopped by the debugger when it calls main(). (If you've ever wondered where main() gets called from, now you know!). You can now step through the program, a line at a time, by pressing n. If you get to a function call, you can step into it by pressing s. Once you're in a function call, you can return from stepping into a function call by pressing f. You can also use up and down to take a quick look at the caller. Here's a simple example of how to spot a mistake in a program with gdb. This is our program (with a deliberate mistake): #include <stdio.h> int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } This program sets i to be 5 and passes it to a function bazz() which prints out the number we gave it. When we compile and run the program we get $ cc -g -o temp temp.c $ ./temp This is my program anint = 4231 That wasn't what we expected! Time to see what's going on!$ gdb temp GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) break main Skip the set-up code Breakpoint 1 at 0x160f: file temp.c, line 9. gdb puts breakpoint at main() (gdb) run Run as far as main() Starting program: /home/james/tmp/temp Program starts running Breakpoint 1, main () at temp.c:9 gdb stops at main() (gdb) n Go to next line This is my program Program prints out (gdb) s step into bazz() bazz (anint=4231) at temp.c:17 gdb displays stack frame (gdb) Hang on a minute! How did anint get to be 4231? Didn't we set it to be 5 in main()? Let's move up to main() and have a look. (gdb) up Move up call stack #1 0x1625 in main () at temp.c:11 gdb displays stack frame (gdb) p i Show us the value of i $1 = 4231 gdb displays 4231 Oh dear! Looking at the code, we forgot to initialise i. We meant to put … main() { int i; i = 5; printf("This is my program\n"); &hellip but we left the i=5; line out. As we didn't initialise i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be 4231. gdb displays the stack frame every time we go into or out of a function, even if we're using up and down to move around the call stack. This shows the name of the function and the values of its arguments, which helps us keep track of where we are and what's going on. (The stack is a storage area where the program stores information about the arguments passed to functions and where to go when it returns from a function call). Examining a core file A core file is basically a file which contains the complete state of the process when it crashed. In the good old days, programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called progname.core instead of just core, to make it clearer which program a core file belongs to. To examine a core file, start up gdb in the usual way. Instead of typing break or run, type (gdb) core progname.core If you're not in the same directory as the core file, you'll have to do dir /path/to/core/file first. You should see something like this: $ gdb a.out GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) core a.out.core Core was generated by `a.out'. Program terminated with signal 11, Segmentation fault. Cannot access memory at address 0x7020796d. #0 0x164a in bazz (anint=0x5) at temp.c:17 (gdb) In this case, the program was called a.out, so the core file is called a.out.core. We can see that the program crashed due to trying to access an area in memory that was not available to it in a function called bazz. Sometimes it's useful to be able to see how a function was called, as the problem could have occurred a long way up the call stack in a complex program. The bt command causes gdb to print out a back-trace of the call stack: (gdb) bt #0 0x164a in bazz (anint=0x5) at temp.c:17 #1 0xefbfd888 in end () #2 0x162c in main () at temp.c:11 (gdb)The end() function is called when a program crashes; in this case, the bazz() function was called from main(). Attaching to a running program One of the neatest features about gdb is that it can attach to a program that's already running. Of course, that assumes you have sufficient permissions to do so. A common problem is when you are stepping through a program that forks, and you want to trace the child, but the debugger will only let you trace the parent. What you do is start up another gdb, use ps to find the process ID for the child, and do(gdb) attach pid in gdb, and then debug as usual. That's all very well, you're probably thinking, but by the time I've done that, the child process will be over the hill and far away. Fear not, gentle reader, here's how to do it (courtesy of the gdb info pages): &hellip if ((pid = fork()) < 0) /* _Always_ check this */ error(); else if (pid == 0) { /* child */ int PauseMode = 1; while (PauseMode) sleep(10); /* Wait until someone attaches to us */ &hellip } else { /* parent */ &hellip Now all you have to do is attach to the child, set PauseMode to 0, and wait for the sleep() call to return! Using Emacs as a Development Environment Emacs Unfortunately, Unix systems don't come with the kind of everything-you-ever-wanted-and-lots-more-you-didn't-in-one-gigantic-package integrated development environments that other systems have.At least, not unless you pay out very large sums of money. However, it is possible to set up your own environment. It may not be as pretty, and it may not be quite as integrated, but you can set it up the way you want it. And it's free. And you have the source to it. The key to it all is Emacs. Now there are some people who loathe it, but many who love it. If you're one of the former, I'm afraid this section will hold little of interest to you. Also, you'll need a fair amount of memory to run it—I'd recommend 8MB in text mode and 16MB in X as the bare minimum to get reasonable performance. Emacs is basically a highly customisable editor—indeed, it has been customised to the point where it's more like an operating system than an editor! Many developers and sysadmins do in fact spend practically all their time working inside Emacs, leaving it only to log out. It's impossible even to summarise everything Emacs can do here, but here are some of the features of interest to developers: Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to start/end of block expression, etc, etc. Pull-down menus and online help. Language-dependent syntax highlighting and indentation. Completely customisable. You can compile and debug programs within Emacs. On a compilation error, you can jump to the offending line of source code. Friendly-ish front-end to the info program used for reading GNU hypertext documentation, including the documentation on Emacs itself. Friendly front-end to gdb, allowing you to look at the source code as you step through your program. You can read Usenet news and mail while your program is compiling. And doubtless many more that I've overlooked. Emacs can be installed on FreeBSD using the Emacs +URL="../../ports/editors.html">the Emacs port. Once it's installed, start it up and do C-h t to read an Emacs tutorial—that means hold down the control key, press h, let go of the control key, and then press t. (Alternatively, you can you use the mouse to select Emacs Tutorial from the Help menu). Although Emacs does have menus, it's well worth learning the key bindings, as it's much quicker when you're editing something to press a couple of keys than to try and find the mouse and then click on the right place. And, when you're talking to seasoned Emacs users, you'll find they often casually throw around expressions like M-x replace-s RET foo RET bar RET so it's useful to know what they mean. And in any case, Emacs has far too many useful functions for them to all fit on the menu bars. Fortunately, it's quite easy to pick up the key-bindings, as they're displayed next to the menu item. My advice is to use the menu item for, say, opening a file until you understand how it works and feel confident with it, then try doing C-x C-f. When you're happy with that, move on to another menu command. If you can't remember what a particular combination of keys does, select Describe Key from the Help menu and type it in—Emacs will tell you what it does. You can also use the Command Apropos menu item to find out all the commands which contain a particular word in them, with the key binding next to it. By the way, the expression above means hold down the Meta key, press x, release the Meta key, type replace-s (short for replace-string—another feature of Emacs is that you can abbreviate commands), press the return key, type foo (the string you want replaced), press the return key, type bar (the string you want to replace foo with) and press return again. Emacs will then do the search-and-replace operation you've just requested. If you're wondering what on earth the Meta key is, it's a special key that many Unix workstations have. Unfortunately, PC's don't have one, so it's usually the alt key (or if you're unlucky, the escape key). Oh, and to get out of Emacs, do C-x C-c (that means hold down the control key, press c, press x and release the control key). If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore the bit in the documentation where it says C-z is the usual way to leave Emacs—that leaves Emacs hanging around in the background, and is only really useful if you're on a system which doesn't have virtual terminals). Configuring Emacs Emacs does many wonderful things; some of them are built in, some of them need to be configured. Instead of using a proprietary macro language for configuration, Emacs uses a version of Lisp specially adapted for editors, known as Emacs Lisp. This can be quite useful if you want to go on and learn something like Common Lisp, as it's considerably smaller than Common Lisp (although still quite big!). The best way to learn Emacs Lisp is to download the Emacs Tutorial However, there's no need to actually know any Lisp to get started with configuring Emacs, as I've included a sample .emacs file, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it's already running; it will read the commands from the file and (hopefully) give you a useful basic setup. A sample <filename>.emacs</filename> file Unfortunately, there's far too much here to explain it in detail; however there are one or two points worth mentioning. Everything beginning with a ; is a comment and is ignored by Emacs. In the first line, the -*- Emacs-Lisp -*- is so that we can edit the .emacs file itself within Emacs and get all the fancy features for editing Emacs Lisp. Emacs usually tries to guess this based on the filename, and may not get it right for .emacs. The tab key is bound to an indentation function in some modes, so when you press the tab key, it will indent the current line of code. If you want to put a tab character in whatever you're writing, hold the control key down while you're pressing the tab key. This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by guessing the language from the filename. Emacs already has a pre-defined function called next-error. In a compilation output window, this allows you to move from one compilation error to the next by doing M-n; we define a complementary function, previous-error, that allows you to go to a previous error by doing M-p. The nicest feature of all is that C-c C-c will open up the source file in which the error occurred and jump to the appropriate line. We enable Emacs's ability to act as a server, so that if you're doing something outside Emacs and you want to edit a file, you can just type in $ emacsclient filename and then you can edit the file in your Emacs!Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit a file. A sample <filename>.emacs</filename> file ;; -*-Emacs-Lisp-*- ;; This file is designed to be re-evaled; use the variable first-time ;; to avoid any problems with this. (defvar first-time t "Flag signifying this is the first time that .emacs has been evaled") ;; Meta (global-set-key "\M- " 'set-mark-command) (global-set-key "\M-\C-h" 'backward-kill-word) (global-set-key "\M-\C-r" 'query-replace) (global-set-key "\M-r" 'replace-string) (global-set-key "\M-g" 'goto-line) (global-set-key "\M-h" 'help-command) ;; Function keys (global-set-key [f1] 'manual-entry) (global-set-key [f2] 'info) (global-set-key [f3] 'repeat-complex-command) (global-set-key [f4] 'advertised-undo) (global-set-key [f5] 'eval-current-buffer) (global-set-key [f6] 'buffer-menu) (global-set-key [f7] 'other-window) (global-set-key [f8] 'find-file) (global-set-key [f9] 'save-buffer) (global-set-key [f10] 'next-error) (global-set-key [f11] 'compile) (global-set-key [f12] 'grep) (global-set-key [C-f1] 'compile) (global-set-key [C-f2] 'grep) (global-set-key [C-f3] 'next-error) (global-set-key [C-f4] 'previous-error) (global-set-key [C-f5] 'display-faces) (global-set-key [C-f8] 'dired) (global-set-key [C-f10] 'kill-compilation) ;; Keypad bindings (global-set-key [up] "\C-p") (global-set-key [down] "\C-n") (global-set-key [left] "\C-b") (global-set-key [right] "\C-f") (global-set-key [home] "\C-a") (global-set-key [end] "\C-e") (global-set-key [prior] "\M-v") (global-set-key [next] "\C-v") (global-set-key [C-up] "\M-\C-b") (global-set-key [C-down] "\M-\C-f") (global-set-key [C-left] "\M-b") (global-set-key [C-right] "\M-f") (global-set-key [C-home] "\M-<") (global-set-key [C-end] "\M->") (global-set-key [C-prior] "\M-<") (global-set-key [C-next] "\M->") ;; Mouse (global-set-key [mouse-3] 'imenu) ;; Misc (global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab. (setq backup-by-copying-when-mismatch t) ;; Treat 'y' or <CR> as yes, 'n' as no. (fset 'yes-or-no-p 'y-or-n-p) (define-key query-replace-map [return] 'act) (define-key query-replace-map [?\C-m] 'act) ;; Load packages (require 'desktop) (require 'tar-mode) ;; Pretty diff mode (autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files-remote "ediff" "Intelligent Emacs interface to diff") (if first-time (setq auto-mode-alist (append '(("\\.cpp$" . c++-mode) ("\\.hpp$" . c++-mode) ("\\.lsp$" . lisp-mode) ("\\.scm$" . scheme-mode) ("\\.pl$" . perl-mode) ) auto-mode-alist))) ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") (defvar font-lock-mode-keyword-alist '((c++-c-mode . c-font-lock-keywords) (perl-mode . perl-font-lock-keywords)) "Associations between modes and keywords") (defun font-lock-auto-mode-select () "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list" (if (memq major-mode font-lock-auto-mode-list) (progn (font-lock-mode t)) ) ) (global-set-key [M-f1] 'font-lock-fontify-buffer) ;; New dabbrev stuff ;(require 'new-dabbrev) (setq dabbrev-always-check-other-buffers t) (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") (add-hook 'emacs-lisp-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'c-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'text-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) t) (set (make-local-variable 'dabbrev-case-replace) t))) ;; C++ and C mode... (defun my-c++-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c++-mode-map "\C-ce" 'c-comment-edit) (setq c++-auto-hungry-initial-state 'none) (setq c++-delete-function 'backward-delete-char) (setq c++-tab-always-indent t) (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c++-empty-arglist-indent 4)) (defun my-c-mode-hook () (setq tab-width 4) (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c-mode-map "\C-ce" 'c-comment-edit) (setq c-auto-hungry-initial-state 'none) (setq c-delete-function 'backward-delete-char) (setq c-tab-always-indent t) ;; BSD-ish indentation style (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c-brace-offset -4) (setq c-argdecl-indent 0) (setq c-label-offset -4)) ;; Perl mode (defun my-perl-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (setq perl-indent-level 4) (setq perl-continued-statement-offset 4)) ;; Scheme mode... (defun my-scheme-mode-hook () (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent)) ;; Emacs-Lisp mode... (defun my-lisp-mode-hook () (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key lisp-mode-map "\C-i" 'lisp-indent-line) (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp)) ;; Add all of the hooks... (add-hook 'c++-mode-hook 'my-c++-mode-hook) (add-hook 'c-mode-hook 'my-c-mode-hook) (add-hook 'scheme-mode-hook 'my-scheme-mode-hook) (add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'perl-mode-hook 'my-perl-mode-hook) ;; Complement to next-error (defun previous-error (n) "Visit previous compilation error message and corresponding source code." (interactive "p") (next-error (- n))) ;; Misc... (transient-mark-mode 1) (setq mark-even-if-inactive t) (setq visible-bell nil) (setq next-line-add-newlines nil) (setq compile-command "make") (setq suggest-key-bindings nil) (put 'eval-expression 'disabled nil) (put 'narrow-to-region 'disabled nil) (put 'set-goal-column 'disabled nil) ;; Elisp archive searching (autoload 'format-lisp-code-directory "lispdir" nil t) (autoload 'lisp-dir-apropos "lispdir" nil t) (autoload 'lisp-dir-retrieve "lispdir" nil t) (autoload 'lisp-dir-verify "lispdir" nil t) ;; Font lock mode (defun my-make-face (face colour &optional bold) "Create a face from a colour and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face colour) (if bold (make-face-bold face)) ) (if (eq window-system 'x) (progn (my-make-face 'blue "blue") (my-make-face 'red "red") (my-make-face 'green "dark green") (setq font-lock-comment-face 'blue) (setq font-lock-string-face 'bold) (setq font-lock-type-face 'bold) (setq font-lock-keyword-face 'bold) (setq font-lock-function-name-face 'red) (setq font-lock-doc-string-face 'green) (add-hook 'find-file-hooks 'font-lock-auto-mode-select) (setq baud-rate 1000000) (global-set-key "\C-cmm" 'menu-bar-mode) (global-set-key "\C-cms" 'scroll-bar-mode) (global-set-key [backspace] 'backward-delete-char) ; (global-set-key [delete] 'delete-char) (standard-display-european t) (load-library "iso-transl"))) ;; X11 or PC using direct screen writes (if window-system (progn ;; (global-set-key [M-f1] 'hilit-repaint-command) ;; (global-set-key [M-f2] [?\C-u M-f1]) (setq hilit-mode-enable-list '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode scheme-mode) hilit-auto-highlight nil hilit-auto-rehighlight 'visible hilit-inhibit-hooks nil hilit-inhibit-rebinding t) (require 'hilit19) (require 'paren)) (setq baud-rate 2400) ; For slow serial connections ) ;; TTY type terminal (if (and (not window-system) (not (equal system-type 'ms-dos))) (progn (if first-time (progn (keyboard-translate ?\C-h ?\C-?) (keyboard-translate ?\C-? ?\C-h))))) ;; Under UNIX (if (not (equal system-type 'ms-dos)) (progn (if first-time (server-start)))) ;; Add any face changes here (add-hook 'term-setup-hook 'my-term-setup-hook) (defun my-term-setup-hook () (if (eq window-system 'pc) (progn ;; (set-face-background 'default "red") ))) ;; Restore the "desktop" - do this as late as possible (if first-time (progn (desktop-load-default) (desktop-read))) ;; Indicate that this file has been read at least once (setq first-time nil) ;; No need to debug anything now (setq debug-on-error nil) ;; All done (message "All done, %s%s" (user-login-name) ".") Extending the Range of Languages Emacs Understands Now, this is all very well if you only want to program in the languages already catered for in the .emacs file (C, C++, Perl, Lisp and Scheme), but what happens if a new language called whizbang comes out, full of exciting features? The first thing to do is find out if whizbang comes with any files that tell Emacs about the language. These usually end in .el, short for Emacs Lisp. For example, if whizbang is a FreeBSD port, we can locate these files by doing $ find /usr/ports/lang/whizbang -name "*.el" -print and install them by copying them into the Emacs site Lisp directory. On FreeBSD 2.1.0-RELEASE, this is /usr/local/share/emacs/site-lisp. So for example, if the output from the find command was /usr/ports/lang/whizbang/work/misc/whizbang.el we would do $ cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp Next, we need to decide what extension whizbang source files have. Let's say for the sake of argument that they all end in .wiz. We need to add an entry to our .emacs file to make sure Emacs will be able to use the information in whizbang.el. Find the auto-mode-alist entry in .emacs and add a line for whizbang, such as: … ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) This means that Emacs will automatically go into whizbang-mode when you edit a file ending in .wiz. Just below this, you'll find the font-lock-auto-mode-list entry. Add whizbang-mode to it like so: ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") This means that Emacs will always enable font-lock-mode (ie syntax highlighting) when editing a .wiz file. And that's all that's needed. If there's anything else you want done automatically when you open up a .wiz file, you can add a whizbang-mode hook (see my-scheme-mode-hook for a simple example that adds auto-indent). Further Reading Brian Harvey and Matthew Wright Simply Scheme MIT 1994. ISBN 0-262-08226-8 Randall Schwartz Learning Perl O'Reilly 1993 ISBN 1-56592-042-2 Patrick Henry Winston and Berthold Klaus Paul Horn Lisp (3rd Edition) Addison-Wesley 1989 ISBN 0-201-08319-1 Brian W. Kernighan and Rob Pike The Unix Programming Environment Prentice-Hall 1984 ISBN 0-13-937681-X Brian W. Kernighan and Dennis M. Ritchie The C Programming Language (2nd Edition) Prentice-Hall 1988 ISBN 0-13-110362-8 Bjarne Stroustrup The C++ Programming Language Addison-Wesley 1991 ISBN 0-201-53992-6 W. Richard Stevens Advanced Programming in the Unix Environment Addison-Wesley 1992 ISBN 0-201-56317-7 W. Richard Stevens Unix Network Programming Prentice-Hall 1990 ISBN 0-13-949876-1