diff --git a/documentation/content/de/books/developers-handbook/tools/_index.adoc b/documentation/content/de/books/developers-handbook/tools/_index.adoc index 855f9345e4..f6b6f1c2bc 100644 --- a/documentation/content/de/books/developers-handbook/tools/_index.adoc +++ b/documentation/content/de/books/developers-handbook/tools/_index.adoc @@ -1,1241 +1,1241 @@ --- title: Kapitel 2. Werkzeuge zur Programmierung authors: - author: James Raynard - author: Murray Stokely prev: books/developers-handbook/introduction next: books/developers-handbook/secure showBookMenu: true weight: 3 path: "/books/developers-handbook/tools/" --- [[tools]] = Werkzeuge zur Programmierung :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 2 :partnums: :source-highlighter: rouge :experimental: :c-plus-plus-command: c++ :clang-plus-plus-command: clang++ :gcc-plus-plus: g++ :lg-plus-plus: -lg++ :lstdc-plus-plus: -lstdc++ :images-path: books/developers-handbook/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[tools-synopsis]] == Überblick Dieses Kapitel ist eine Einführung in die Benutzung einiger der Werkzeuge zur Programmierung die mit FreeBSD ausgeliefert werden. Trotzdem ist vieles auch auf verschiedene andere Versionen von UNIX(R) übertragbar. Dieses Kapitel soll _kein_ Versuch sein Programmierung detailliert zu beschreiben. Der größte Teil dieses Kapitels setzt wenige oder gar keine Programmierkenntnisse voraus, dennoch sollten die meisten Programmierer etwas Sinnvolles darin finden. [[tools-intro]] == Zusammenfassung FreeBSD bietet eine exzellente Entwicklungsumgebung. Compiler für C und C++, sowie ein Assembler sind im Basissystem enthalten. Natürlich finden sich auch klassische UNIX(R)-Werkzeuge wie `sed` und `awk`. Sollte das nicht genug sein, finden sich zahlreiche weitere Compiler und Interpreter in der Ports-Sammlung. Der folgende Abschnitt, <>, zählt ein paar der verfügbaren Optionen auf. FreeBSD ist kompatibel zu vielen Standards wie POSIX(R) und ANSI C, sowie zu seinem eigenen BSD Erbe. So ist es möglich Anwendungen zu schreiben, welche ohne oder zumindest ohne wesentliche Änderungen auf einer großen Zahl an Plattformen kompilieren und laufen werden. Allerdings können all diese Möglichkeiten anfangs etwas überwältigend sein, wenn Sie vorher nie Programme auf einem UNIX(R)-System geschrieben haben. Dieses Dokument hat die Zielsetzung ihnen beim Einstieg zu helfen ohne allzu weit in fortgeschrittene Themen vorzudringen. Die Intention ist, daß dieses Dokument ihnen ausreichend Basiswissen vermittelt und die weitergehende Dokumentation sinnvoll nutzen zu können. Der größte Teil dieses Dokuments erfordert wenige oder gar keine Kenntnisse in der Programmierung, es werden trotzdem Basiswissen im Umgang mit UNIX(R) und die Bereitschaft zu lernen vorausgesetzt! [[tools-programming]] == Einführung in die Programmierung Ein Programm ist eine Zusammenstellung von Anweisungen, die den Computer auffordern verschiedenste Dinge zu tun. Dieser Abschnitt gibt ihnen einen Überblick über die beiden wesentlichen Methoden diese Anweisungen oder "Befehle", wie man diese Anweisungen üblicherweise nennt, zu geben. Die eine Methode nutzt einen _Interpreter_, die andere einen _Compiler_. Da menschliche Sprachen für einen Computer nicht unmissverständlich sind, werden diese Befehle in einer Sprache geschrieben die speziell für diesen Zweck gedacht ist. === Interpreter Mit einem Interpreter ist die Sprache vielmehr eine Umgebung, in der Sie ein Kommando an der Kommandozeile eingeben welches dann von der Umgebung ausgeführt wird. Für kompliziertere Programme können Sie die Befehle in eine Datei schreiben und den Interpreter dazu bringen diese Datei zu laden und die enthaltenen Befehle auszuführen. Falls etwas schief geht werden viele Interpreter Sie an einen Debugger weiterleiten. Der Vorteil hierbei ist, das Sie das Ergebnis ihres Befehls direkt sehen und Fehler sofort korrigiert werden können. Der größte Nachteil bei dieser Methode entsteht, wenn Sie ihr Programm mit jemandem teilen wollen. Diese Person muss den selben Interpreter nutzen wie Sie es tun und Sie muss wissen wie dieser zu bedienen ist. Zudem werden Benutzer es nicht begrüßen sich in einem Debugger wiederzufinden, wenn Sie einmal die falsche Taste drücken! Bei einem Blick auf die Leistungsfähigkeit brauchen Interpreter oftmals viel Speicher und erzeugen den Code nicht so effizient wie Compiler. Meiner Meinung nach sind interpretierte Sprachen der beste Anfang, wenn Sie bisher noch nicht programmiert haben. Diese Art von Umgebung findet man typischerweise bei Sprachen wie Lisp, Smalltalk, Perl und Basic. Man könnte auch sagen, dass die UNIX(R) Shell (`sh`, `csh`) für sich bereits einen Interpreter darstellt und viele Leute schreiben tatsächlich Shell "Scripten" um sich bei einigen "Haushaltsaufgaben" auf ihren Maschinen helfen zu lassen. Tatsächlich war es ein wesentlicher Teil der originalen UNIX(R) Philosophie eine große Zahl an kleinen Hilfsprogrammen zur Verfügung zu stellen, welche mittels eines Shellskripts miteinander kombiniert werden um bestimmte Aufgaben zu übernehmen. === Für FreeBSD verfügbare Interpreter Im folgenden eine Liste der über die FreeBSD Ports-Sammlung verfügbaren Interpreter einschließlich einer kurzen Erörterung der populären interpretierten Sprachen. Anleitungen wie man Anwendungen aus der Ports-Sammlung erhält und installiert können Sie dem Kapitel extref:{handbook}ports/[Benutzen der Ports-Sammlung, ports-using] aus dem FreeBSD Handbuch entnehmen. BASIC:: Kurz für Beginner's All-purpose Symbolic Instruction Code. Entwickelt in den 50er Jahren um Studenten in Programmierung zu unterrichten, wurde BASIC in den 80er Jahren mit jedem anständigen Personal Computer ausgeliefert und war für viele Programmierer die erste Programmiersprache. BASIC ist auch die Grundlage für Visual Basic. + Der Bywater Basic Interpreter findet sich in der Ports-Sammlung unter package:lang/bwbasic[] und Phil Cockroft's Basic Interpreter (auch bekannt als Rabbit Basic) findet sich unter package:lang/pbasic[]. Lisp:: Diese Sprache wurde in den späten 50er Jahren als Alternative zu den, zu dieser Zeit populären, "zahlenverarbeitenden" Sprachen entwickelt. Anstelle auf Zahlen basiert Lisp auf Listen; tatsächlich ist der Name Lisp eine Kurzform für "List Processing" (Listen abarbeiten). Sehr populär fü AI (Artificial Intelligence/ künstliche Intelligez) (Fach-) Kreisen. + Lisp ist eine extrem kraftvolle und durchdachte Sprache, kann aber auch recht groß und unhandlich sein. + Zahlreiche Ausformungen von Lisp, die auf UNIX(R) Systemen laufen sind über die Ports-Sammlung verfügbar. GNU Common Lisp befindet sich in package:lang/gcl[]. CLISP von Bruno Haible und Michael Stoll ist in package:lang/clisp[] zu finden. Für CMUCL, welches auch einen hoch-optimierten Compiler enthält, oder einfachere Ausformungen wie SLisp, das die meisten gängigen Lisp Konstrukte in wenigen hundert Zeilen C Code enthält sind in package:lang/cmucl[] und package:lang/slisp[] ebenfalls enthalten. Perl:: Unter Systemadministratoren zum Schreiben von Skripten sehr beliebt; wird häufig auch auf World Wide Web Servern verwendet, um CGI-Skripte zu schreiben. + Perl ist in der Ports-Sammlung unter package:lang/perl5.8[] für alle FreeBSD-Versionen verfügbar, und wird im Basissystem von 4.x als `/usr/bin/perl` installiert. Scheme:: Ein Dialekt von Lisp, der kompakter und sauberer als Common Lisp ist. Dieser Dialekt ist an Universitäten sehr beliebt, da er zum einen für den Unterricht im Grundstudium einfach genug ist, und zum anderen ein ausreichend hohes Abstraktionsniveau für den Einsatz in der Forschung bietet. + Scheme ist in der Ports-Sammlung in Form des Elk Scheme Interpreters als package:lang/elk[] verfügbar. Den MIT Scheme Interpreter findet man unter package:lang/mit-scheme[], und den SCM Scheme Interpreter unter package:lang/scm[]. Icon:: Icon ist eine Hochsprache mit ausgereiften Möglichkeiten zur Verarbeitung von Zeichenketten und Strukturen. Die unter FreeBSD verfügbare Version von Icon steht in der Ports-Sammlung unter package:lang/icon[] zur Verfügung. Logo:: Logo ist eine leicht zu erlernende Programmiersprache, welche in vielen Kursen als einführende Programmiersprache gewählt wird. Sie ist ein ideales Arbeitswerkzeug beim Unterricht mit jungen Menschen, da mit ihr die Erstellung komplizierter geometrischer Oberflächen selbst für kleine Kinder einfach ist. + Die für FreeBSD aktuellste, verfügbare Version findet man in der Ports-Sammlung unter package:lang/logo[]. Python:: Python ist eine objektorientierte, interpretierte Programmiersprache. Die Verfechter von Python argumentieren, daß sie eine der besten Programmiersprachen für Programmieranfänger sei, da sie einfach zu erlernen ist, und anderen populären interpretierten Programmiersprachen, welche zur Entwicklung großer und komplexer Anwendungen verwendet werden, in nichts nachsteht (Perl und Tcl sind zwei solcher bekannten Programmiersprachen). + Die aktuellste Version von Python ist in der Ports-Sammlung unter package:lang/python[] verfügbar. Ruby:: Ruby ist eine interpretierte und rein objektorientierte Programmiersprache. Sie wurde wegen ihrer leicht verständlichen Syntax, ihrer Flexibilität und der Möglichkeit, große und komplexe Programme einfach zu entwickeln und zu pflegen, populär. + Ruby ist in der Ports-Sammlung unter package:lang/ruby18[] verfügbar. Tcl und Tk:: Tcl ist eine einbettbare, interpretierte Programmiersprache, welche aufgrund ihrer Portierbarkeit auf viele unterschiedliche Plattformen eine weite Verbreitung erfahren hat. Sie kann sowohl für die schnelle Entwicklung kleinerer Prototypen, als auch (in Verbindung mit Tk, einem GUI Toolkit) vollwertiger, ausgereifter Programme verwendet werden. + -Es sind mehrere Versionen von Tcl als Ports für FreeBSD verfügbar. Die aktuellste Version, Tcl 8.5, ist unter package:lang/tcl85[] verfügbar. +Es sind mehrere Versionen von Tcl als Ports für FreeBSD verfügbar. Die aktuellste Version, Tcl 8.7, ist unter package:lang/tcl87[] verfügbar. === Compiler Compiler sind eher anders. Zuerst schreibt man seinen Code unter Verwendung eines Editors in eine Datei (oder mehrere Dateien). Anschließend ruft man den Compiler auf um zu sehen, ob dieser das Programm annimmt. Wenn das Programm nicht kompiliert werden konnte, muß man die Zähne zusammenbeissen und wieder zum Editor zurückkehren; falls das Programm kompiliert und eine ausführbare Anwendung erzeugt wurde, kann man diese über eine Eingabeaufforderung oder über einen Debugger aufrufen um zu sehen, ob sie auch funktioniert. Offensichtlich ist diese Art der Programmierung nicht so direkt wie die Verwendung eines Interpreters. Jedoch sind auf diese Weise viele Dinge möglich, die mit einem Interpreter nur sehr schwer oder überhaupt nicht realisierbar wären, wie z.B. das Schreiben von Code, der sehr eng mit dem Betriebsystem zusammen arbeitet-oder das Schreiben eines eigenen Betriebsystems selbst! Des weiteren ist so das Erzeugen von sehr effizientem Code möglich, da sich der Compiler für die Optimierung Zeit nehmen kann, was bei einem Interpreter inakzeptabel wäre. Ferner ist das Verbreiten von Programmen, welche für einen Compiler geschrieben wurden, einfacher als welche, die für einen Interpreter geschrieben wurden-man muss in ersterem Fall nur die ausführbare Datei verbreiten, vorausgesetzt, daß das gleiche Betriebssystem verwendet wird. Programmiersprachen, die kompiliert werden, sind unter anderem Pascal, C und C++. C und C++ sind eher unbarmherzige Programmiersprachen und daher eher für erfahrene Programmierer gedacht; Pascal auf der anderen Seite wurde zu Ausbildungszwecken entworfen, und stellt daher eine einsteigerfreundliche Programmiersprache dar. FreeBSD beinhaltet im Basissystem keine Unterstützung für Pascal, stellt jedoch über die Ports-Sammlung den Free Pascal Compiler unter package:lang/fpc[] zur Verfügung. Da der editier-kompilier-ausführ-debug-Kreislauf unter Verwendung mehrerer Programme eher mühsam ist haben viele Hersteller von Compilern integrierte Entwicklungsumgebungen (Integrated Development Environment; auch kurz IDE) entwickelt. FreeBSD bietet zwar im Basissystem keine IDE an, stellt jedoch über die Ports-Sammlung IDEs wie package:devel/kdevelop[] oder Emacs zur Verfügung, wobei letztere weit verbreitet ist. Die Verwendung von Emacs als IDE wird unter <> diskutiert. [[tools-compiling]] == Kompilieren mit dem `cc` Dieser Abschnitt behandelt ausschließlich den GNU Compiler für C und C++, da dieser bereits im Basissystem von FreeBSD enthalten ist. Er kann mittels ``cc`` oder `gcc` aufgerufen werden. Die Details zur Erstellung einer Anwendung mit einem Interpreter variieren zwischen verschiedenen Interpretern mehr oder weniger stark, und werden meist ausführlich in der zugehörigen Dokumentation oder Online-Hilfe beschrieben. Sobald Sie Ihr Meisterwerk fertig geschrieben haben besteht der nächste Schritt darin, dieses (hoffentlich!) unter FreeBSD zum Laufen zu bekommen. Dies beinhaltet üblicherweise mehrere Schritte, wobei jeder einzelne Schritt von einem separaten Programm durchgeführt wird. [.procedure] ==== . Aufbereiten Ihres Quelltextes durch Entfernen von Kommentaren, sowie weiteren Tricks wie das Ersetzen von Macros in C. . Überprüfen der Syntax Ihres Quelltextes, um die Einhaltung der Sprachregeln sicherzustellen. Wenn Sie diese verletzt haben werden entsprechende Fehlermeldungen Ihnen dies mitteilen! . Übersetzen des Quelltextes in Assemblersprache -diese ist dem eigentlichen Maschinencode schon sehr nahe, jedoch immer noch für Menschen lesbar. Angeblich. . Übersetzen der Assemblersprache in Maschinencode-genau, wir sprechen hier von Bits und Bytes, Einsen und Nullen. . Überprüfen, ob Sie Dinge wie Funktionen und globale Variablen in einheitlicher Weise verwendet haben. Wenn Sie z.B. eine nicht existierende Funktion aufgerufen haben, wird eine entsprechende Fehlermeldung Ihnen dies mitteilen. . Wenn aus mehreren Quelltextdateien eine ausführbare Datei erstellt werden soll wird herausgefunden, wie die einzelnen Codeteile zusammengefügt werden müssen. . Ausarbeiten, wie das Programm aussehen muss, damit der Lader zur Laufzeit des Systems dieses in den Speicher laden und ausführen kann. . Endgültiges Schreiben der ausführbaren Datei in das Dateisystem. ==== Das Wort _kompilieren_ wird häufig für die Schritte 1 bis 4 verwendet-die anderen werden mit dem Wort _verlinken_ zusammengefasst. Manchmal wird Schritt 1 auch als _Pre-Processing_ und die Schritte 3-4 als _assemblieren_ bezeichnet. Glücklicherweise werden alle diese Details vor Ihnen verborgen, da `cc` ein Frontend ist, welches sich um die Ausführung all dieser Programme mit den richtigen Argumenten für Sie kümmert; einfaches eingeben von [source,shell] .... % cc foobar.c .... führt zur Übersetzung von [.filename]#foobar.c# durch alle bereits erwähnten Schritte. Wenn Sie mehr als eine Datei übersetzen wollen müssen Sie etwas wie folgt eingeben [source,shell] .... % cc foo.c bar.c .... Beachten Sie, daß die Überprüfung der Syntax genau dies tut-das reine Überprüfen der Syntax. Es findet keine Überprüfung bzgl. logischer Fehler statt, die Sie vielleicht gemacht haben, wie z.B. das Programm in eine Endlosschleife zu versetzen, oder Bubble Sort zu verwenden, wenn Sie eigentlich Binary Sort benutzen wollten. Es gibt haufenweise Optionen für `cc`, die alle in der zugehörigen Manualpage beschrieben werden. Im Folgenden werden ein paar der wichtigsten Optionen mit Beispielen ihrer Anwendung gezeigt. `-o _filename_`:: Die Name der Ausgabedatei. Wenn Sie diese Option nicht verwenden erstellt `cc` eine Datei mit dem Namen [.filename]#a.out#. + [source,shell] .... % cc foobar.c executable is a.out % cc -o foobar foobar.c executable is foobar .... `-c`:: Dies kompiliert die Datei nur, verlinkt sie jedoch nicht. Nützlich für Spielereien, um die Syntax auf Korrektheit zu überprüfen, oder falls Sie ein [.filename]#Makefile# verwenden. + [source,shell] .... % cc -c foobar.c .... + Dieser Befehl erzeugt eine _Objektdatei_ (nicht ausführbar) mit den Namen [.filename]#foobar.o#. Diese kann mit anderen Objektdateien zusammen zu einer ausführbaren Datei verlinkt werden. `-g`:: Diese Option erzeugt die Debug-Version einer ausführbaren Datei. Dabei fügt der Compiler zusätzliche Informationen darüber, welcher Funktionsaufruf zu welcher Zeile im Quelltext gehört, der ausführbaren Datei hinzu. Ein Debugger kann Ihnen mit Hilfe dieser Information den zugehörigen Quelltext anzeigen, während Sie den Programmverlauf schrittweise verfolgen, was _sehr_ hilfreich sein kann; der Nachteil dabei ist, daß durch die zusätzlichen Informationen das Programm viel größer wird. Normalerweise verwendet man die Option `-g` während der Entwicklung eines Programms, und für die "Release-Version", wenn man von der Korrektheit des Programms überzeugt ist, kompiliert man das Programm dann ohne diese Option. + [source,shell] .... % cc -g foobar.c .... + Mit diesem Befehl wird eine Debug-Version des Programms erzeugt. `-O`:: Diese Option erzeugt eine optimierte Version der ausführbaren Datei. Der Compiler verwendet einige clevere Tricks, um das erzeugte Programm schneller zu machen. Sie können hinter der Option `-O` eine Zahl angeben, um eine höheres Level der Optimierung festzulegen. Dadurch wird jedoch häufig eine fehlerhafte Optimierung seitens des Compilers aufgedeckt. Zum Beispiel erzeugte die Version des `cc`, welche mit dem FreeBSD Release 2.1.0 mitgeliefert wurde, bei Verwendung der Option `-O2` unter bestimmten Umständen falschen Code. + Optimierungen werden normalerweise nur beim Kompilieren von Release-Versionen aktiviert. + [source,shell] .... % cc -O -o foobar foobar.c .... + Durch diesen Befehl wird eine optimierte Version von [.filename]#foobar# erzeugt. Die folgenden drei Flags zwingen den `cc` dazu, Ihren Code auf die Einhaltung der internationalen Standards hin zu überprüfen, welche häufig als ANSI Standards bezeichnet werden, obwohl sie streng genommen zum ISO Standard gehören. `-Wall`:: Aktivieren aller Warnmeldungen, die die Autoren des `cc` für wichtig halten. Trotz des Namens dieser Option werden dadurch nicht sämtliche Warnungen ausgegeben, die der `cc` ausgeben könnte. `-ansi`:: Deaktivieren der meisten, jedoch nicht aller, nicht-ANSI C Eigenschaften, die der `cc` bietet. Trotz des Namens ist durch diese Option nicht sichergestellt, daß Ihr Code diese Standards auch vollständig einhält. `-pedantic`:: Deaktivieren _aller_ Eigenschaften des `cc`, welche nicht konform zu ANSI C sind. Ohne diese Flags wird Ihnen der `cc` die Verwendung eigener Erweiterungen des Standards erlauben. Einige dieser Erweiterungen sind zwar sehr nützlich, werden jedoch nicht von anderen Compilern unterstützt-eigentlich ist eines der Hauptziele des Standards, das Leute Code so schreiben können, daß dieser mit jedem Compiler auf beliebigen Systemen funktioniert. Dies wird häufig als _portabler Code_ bezeichnet. Im Allgemeinen sollten Sie versuchen, Ihren Code so portabel wie möglich zu schreiben, da Sie ansonsten eventuell das gesamte Programm noch einmal neu schreiben müssen, falls dieser in einer anderen Umgebung laufen soll-und wer weiß schon was er in ein paar Jahren verwenden wird? [source,shell] .... % cc -Wall -ansi -pedantic -o foobar foobar.c .... Durch diesen Befehl wird eine ausführbare Datei namens [.filename]#foobar# erzeugt, nachdem [.filename]#foobar.c# auf die Einhaltung der Standards überprüft wurde. `-l _library_`:: Mit dieser Option kann eine Bibliothek mit Funktionen angegeben werden, die während des Verlinkens verwendet wird. + Das am häufigsten auftretende Beispiel dieser Option ist die Übersetzung eines Programmes, welches einige der mathematischen Funktionen in C verwendet. Im Gegensatz zu den meisten anderen Plattformen befinden sich diese Funktionen in einer separaten Bibliothek, deren Verwendung Sie dem Compiler explizit mitteilen müssen. + Angenommen eine Bibliothek heißt [.filename]#libirgendwas.a#, dann müssen Sie dem `cc` als Argument `-l _irgendwas_` übergeben. Zum Beispiel heißt die Mathematik-Bibliothek [.filename]#libm.a#, und daher müssen Sie dem `cc` als Argument `-lm` übergeben. Ein typisches "Manko" der Mathematik-Bibliothek ist, daß diese immer die letzte Bibliothek auf der Kommandozeile sein muß. + [source,shell] .... % cc -o foobar foobar.c -lm .... + Durch diesen Befehl werden die Funktionen aus der Mathematik-Bibliothek in [.filename]#foobar# gelinkt. + Wenn Sie {c-plus-plus-command} -Code kompilieren wollen, müssen Sie {lg-plus-plus}, bzw. {lstdc-plus-plus} falls Sie FreeBSD 2.2 oder neuer verwenden, zu Ihrer Kommandozeile hinzufügen, um Ihr Programm gegen die Funktionen der C++ Bibliothek zu linken. Alternativ können Sie anstatt cc auch {c-plus-plus-command} aufrufen, welcher dies für Sie erledigt. C++ kann unter FreeBSD auch als {gcc-plus-plus} aufgerufen werden. + [source,shell] .... % cc -o foobar foobar.cc -lg++ Bei FreeBSD 2.1.6 oder älter % cc -o foobar foobar.cc -lstdc++ Bei FreeBSD 2.2 und neuer % c++ -o foobar foobar.cc .... + Beide Varianten erzeugen eine ausführbare [.filename]##foobar## aus der {c-plus-plus-command} Quelltextdatei [.filename]##foobar.cc##. Beachten Sie bitte, daß auf UNIX(R) Systemen {c-plus-plus-command} Quelltextdateien üblicherweise auf [.filename]##.C##, [.filename]##.cxx## oder [.filename]##.cc## enden, und nicht wie bei MS-DOS(R) auf [.filename]##.cpp## (welche schon anderweitig benutzt wurde). Der `gcc` hat normalerweise anhand dieser Information entschieden, welcher Compiler für die Quelltextdatei zum Einsatz kommen soll; allerdings gilt diese Einschränkung jetzt nicht mehr, und Sie können Ihre {c-plus-plus-command}-Dateien ungestraft auf [.filename]##.cpp## enden lassen! === Häufig auftretende `cc`-Fragen und -Probleme ==== Ich versuche ein Programm zu schreiben, welches die Funktion sin() verwendet, erhalte jedoch eine Fehlermeldung. Was bedeutet diese? Wenn Sie mathematische Funktionen wie `sin()` verwenden wollen, müssen Sie den `cc` anweisen, die Mathematik-Bibliothek wie folgt zu verlinken: [source,shell] .... % cc -o foobar foobar.c -lm .... ==== So, ich habe jetzt dieses einfache Programm als Übung für -lm geschrieben. Alles was es macht ist, 2.1 hoch 6 zu berechnen. Wenn der Compiler Ihren Funktionsaufruf sieht, überprüft er, ob er schon einmal einen Prototypen für diese gesehen hat. Wenn nicht nimmt er als Rückgabewert den Typ [type]#int# an, was sicherlich nicht das ist, was Sie an dieser Stelle wollen. ==== Wie kann ich das korrigieren? Die Prototypen der mathematischen Funktionen befinden sich in der Datei [.filename]#math.h#. Wenn Sie diese Datei in Ihrem Quelltext includen ist der Compiler in der Lage, den Prototypen zu finden, und wird aufhören, seltsame Dinge mit Ihrer Berechnung zu machen! [.programlisting] .... #include #include int main() { ... .... Nach erneutem Compilieren sollte das Folgende bei der Ausführung ausgegeben werden: [source,shell] .... % ./a.out 2.1 ^ 6 = 85.766121 .... Wenn Sie irgendwelche mathematischen Funktionen verwenden sollten Sie _immer_ die Datei [.filename]#math.h# includen und nicht vergessen, Ihr Programm gegen die Mathematik-Bibliothek zu verlinken. ==== Ich habe eine Datei mit dem Namen foobar.c kompiliert, kann jedoch nirgends eine ausführbare Datei namens foobar finden. Wo befindet sich diese? Denken Sie daran, daß der `cc` die ausführbare Datei [.filename]#a.out# nennt, wenn Sie nicht explizit einen Namen angeben. Verwenden Sie in solch einem Fall die Option `-o _filename_`: [source,shell] .... % cc -o foobar foobar.c .... ==== OK, ich habe eine ausführbare Datei namens foobar, ich kann sie sehen, wenn ich ls aufrufe. Gebe ich jedoch foobar in die Kommandozeile ein wird mir gesagt, daß eine Datei mit diesem Namen nicht existiert. Warum kann die Datei nicht gefunden werden? Im Gegensatz zu MS-DOS(R) sucht UNIX(R) nicht im aktuellen Verzeichnis nach einem ausführbaren Programm, das Sie versuchen auszuführen, solange Sie dies nicht explizit mit angeben. Sie können entweder `./foobar` eingeben, was soviel bedeutet wie "führe eine Datei namens [.filename]#foobar# im aktuellen Verzeichnis aus", oder Sie können Ihre Umgebungsvariable `PATH` so erweitern, daß sie ähnlich wie folgt aussieht [source,shell] .... bin:/usr/bin:/usr/local/bin:. .... Der Punkt am Ende bedeutet "siehe im aktuellen Verzeichnis nach, wenn es in keinem der anderen zu finden war". ==== Ich habe meine ausführbare Datei test genannt, allerdings passiert nichts wenn ich diese aufrufe. Was ist hier los? Bei den meisten UNIX(R)-Systeme existiert bereits ein Programm mit dem Namen `test` im Verzeichnis [.filename]#/usr/bin#, und die Shell nimmt dieses, bevor sie im aktuellen Verzeichnis nachsieht. Sie können entweder den folgenden Befehl eingeben: [source,shell] .... % ./test .... oder Sie können einen geeigneteren Namen für Ihr Programm wählen! ==== Ich habe mein Programm kompiliert und bei dessen Aufruf sah zuerst alles gut aus. Jedoch gab es dann eine Fehlermeldung, welche irgendetwas mit core dumped lautete. Was bedeutet das? Der Name _core dump_ stammt noch aus sehr frühen Zeiten von UNIX(R), als die Maschinen noch Kernspeicher zum Speichern von Daten verwendeten. Einfach ausgedrückt, wenn bei einem Programm unter bestimmen Bedingungen ein Fehler auftrat, hat das System den Inhalt des Kernspeichers auf der Festplatte in eine Datei namens [.filename]#core# geschrieben, welche der Programmierer dann näher untersuchen konnte, um die Ursache des Fehlers herauszufinden. ==== Faszinierendes Zeugs, aber was soll ich jetzt machen? Verwenden Sie den `gdb`, um das Speicherabbild zu untersuchen (siehe <>). ==== Als mein Programm den core dump erzeugt hat, sagte es etwas von einem segmentation fault. Was ist das? Diese Meldung heißt im Prinzip, daß Ihr Programm eine illegale Operation mit dem Speicher durchführen wollte; UNIX(R) wurde so entworfen, daß es das andere Programme und das Betriebssystem selbst vor wildgewordenen Programmen schützt. Häufige Ursachen hierfür sind: * Der Versuch, einen NULL-Zeiger zu beschreiben, z.B. + [.programlisting] .... char *foo = NULL; strcpy(foo, "bang!"); .... + * Einen Zeiger zu verwenden, welcher noch nicht initialisiert wurde, z.B. + [.programlisting] .... char *foo; strcpy(foo, "bang!"); .... + Der Zeiger hat einen zufälligen Wert, welcher mit etwas Glück in einen Bereich des Speichers zeigt, der für Ihr Programm nicht verfügbar ist, und der Kernel bricht Ihr Programm ab, bevor es irgendwelchen Schaden anrichten kann. Wenn Sie Pech haben zeigt der Zeiger irgendwo mitten in Ihr eigenes Programm, und verändert dort ihre eigenen Datenstrukturen, was zu sehr seltsamen Fehlern Ihres Programmes führt. * Der Versuch, auf Daten außerhalb eines Arrays zuzugreifen, z.B. + [.programlisting] .... int bar[20]; bar[27] = 6; .... + * Der Versuch, Daten in eine Speicherbereich zu schreiben, der nur lesbar ist, z.B. + [.programlisting] .... char *foo = "My string"; strcpy(foo, "bang!"); .... + UNIX(R)-Compiler speichern häufig feste Zeichenketten wie `"My string"` in nur lesbaren Speicherbereichen ab. * Wenn man unerlaubte Operationen mit `malloc()` und `free()` ausführt, z.B. + [.programlisting] .... char bar[80]; free(bar); .... + oder + [.programlisting] .... char *foo = malloc(27); free(foo); free(foo); .... Einzelne solcher Fehler führen zwar nicht immer zu einem Fehlverhalten des Programms, stellen jedoch immer eine falsche Verwendung dar. Manche Systeme und Compiler sind toleranter als andere, weshalb Programme auf dem einen System einwandfrei laufen, auf dem anderen System jedoch abstürzen. ==== Wenn ich einen core dump erhalte erscheint manchmal die Meldung bus error. In meinem UNIX(R)-Buch steht, daß die Ursache ein Hardwareproblem sei. Der Computer scheint aber weiterhin zu funktionieren. Ist dies wahr? Nein, glücklicherweise nicht (es sei denn Sie haben wirklich ein Hardwareproblem...). Üblicherweise ist dies ein Weg Ihnen mitzuteilen, daß Sie auf Speicher in einer Weise zugegriffen haben, in der Sie dies nicht tun sollten. ==== Diese Sache mit den core dumps hört sich sehr nützlich an, wenn ich so etwas selber an beliebiger Stelle bewirken könnte. Kann ich das tun, oder muß ich warten bis ein Fehler auftritt? Ja, nehmen sie einfach eine andere Konsole oder XTerm und führen Sie [source,shell] .... % ps .... aus, um die Prozess-ID Ihres Programms herauszufinden. Führen Sie anschließend [source,shell] .... % kill -ABRT pid .... aus, wobei [parameter]#_pid_# die Prozess-ID ist, die Sie vorher ermittelt haben. Dies ist nützlich, wenn sich Ihr Programm z.B. in einer Endlosschleife verfangen hat. Sollte Ihr Programm das Signal SIGABRT abfangen, gibt es noch andere Möglichkeiten, die denselben Effekt haben. Alternativ können Sie einen core dump aus Ihrem Programm heraus erstellen, indem Sie die Funktion `abort()` aufrufen. Weitere Informationen darüber können Sie in der Manualpage man:abort[3] nachlesen. Wenn Sie einen core dump von außerhalb Ihres Programms erzeugen wollen, ohne dabei den Prozess abzubrechen, können Sie das Programm `gcore` verwenden. Weitere Informationen dazu finden Sie in der zugehörigen Manualpage man:gcore[1]. [[tools-make]] == Make === Was ist `make`? Wenn Sie an einem einfachen Programm mit nur einer oder zwei Quelltextdateien arbeiten, ist die Eingabe von [source,shell] .... % cc file1.c file2.c .... zwar nicht aufwendig, wird aber mit zunehmender Anzahl der Quelltextdateien sehr lästig-und auch das Kompilieren kann eine Weile dauern. Eine Möglichkeit dies zu umgehen besteht in der Verwendung von Objektdateien, wobei man nur die Quelltextdateien neu kompiliert, die verändert wurden. So könnten wir etwa folgendes erhalten: [source,shell] .... % cc file1.o file2.o … file37.c … .... falls wir seit dem letzten Kompiliervorgang nur die Datei [.filename]#file37.c# verändert haben. Dadurch könnte der Kompiliervorgang um einiges beschleunigt werden, es muß jedoch immer noch alles von Hand eingegeben werden. Oder wir könnten uns ein Shell Skript schreiben. Dieses würde jedoch alles immer wieder neu kompilieren, was bei einem großen Projekt sehr ineffizient wäre. Was ist, wenn wir hunderte von Quelltextdateien hätten? Was ist, wenn wir in einem Team mit anderen Leuten arbeiten würden, die vergessen uns Bescheid zu sagen, falls sie eine der Quelltextdateien verändert haben, die wir ebenfalls benutzen? Vielleicht könnten wir beide Lösungen kombinieren und etwas wie ein Shell Skript schreiben, welches eine Art magische Regel enthalten würde, die feststellt, welche Quelltextdateien neu kompiliert werden müssten. Alles was wir bräuchten wäre ein Programm, das diese Regeln verstehen könnte, da diese Aufgabe etwas zu kompliziert für eine Shell ist. Dieses Programm heißt `make`. Es liest eine Datei namens _makefile_, welche ihm sagt, wie unterschiedliche Dateien voneinander abhängen, und berechnet, welche Dateien neu kompiliert werden müssen und welche nicht. Zum Beispiel könnte eine Regel etwas sagen wie "wenn [.filename]#fromboz.o# älter als [.filename]#fromboz.c# ist, bedeutet dies, daß jemand die Datei [.filename]#fromboz.c# verändert haben muß, und diese daher neu kompiliert werden muß." Das makefile enthält außerdem Regeln die make sagen, _wie_ die Quelltextdatei neu kompiliert werden muß, was dieses Tool noch sehr viel mächtiger macht. Makefiles werden normalerweise im selben Verzeichnis wie die Quelltextdateien abgelegt, zu denen sie gehören, und kann [.filename]#makefile#, [.filename]#Makefile# oder [.filename]#MAKEFILE# heißen. Die meisten Programmierer verwenden den Namen [.filename]#Makefile#, da diese Schreibweise dafür sorgt, daß die Datei gut lesbar ganz oben in der Verzeichnisliste aufgeführt wird. === Beispielhafte Verwendung von `make` Hier ist eine sehr einfache make Datei: [.programlisting] .... foo: foo.c cc -o foo foo.c .... Sie besteht aus zwei Zeilen, einer Abhängigkeitszeile und einer Erzeugungszeile. Die Abhängigkeitszeile hier besteht aus dem Namen des Programms (auch _Ziel_ genannt), gefolgt von einem Doppelpunkt und einem Leerzeichen, und anschließend dem Namen der Quelltextdatei. Wenn `make` diese Zeile liest überprüft es die Existenz von [.filename]#foo#; falls diese Datei existiert vergleicht es das Datum der letzten Änderung von [.filename]#foo# mit der von [.filename]#foo.c#. Falls [.filename]#foo# nicht existiert, oder älter als [.filename]#foo.c# ist, liest es die Erzeugungszeile um herauszufinden, was zu tun ist. Mit anderen Worten, dies ist die Regel die festlegt, wann [.filename]#foo.c# neu kompiliert werden muß. Die Erzeugungszeile beginnt mit einem tab (drücken Sie dazu die kbd:[tab]-Taste) gefolgt von dem Befehl, mit dem Sie [.filename]#foo# manuell erzeugen würden. Wenn [.filename]#foo# veraltet ist, oder nicht existiert, führt `make` diesen Befehl aus, um die Datei zu erzeugen. Mit anderen Worten, dies ist die Regel die make sagt, wie [.filename]#foo.c# kompiliert werden muß. Wenn Sie also `make` eingeben wird dieses sicherstellen, daß [.filename]#foo# bzgl. Ihrer letzten Änderungen an [.filename]#foo.c# auf dem neuesten Stand ist. Dieses Prinzip kann auf [.filename]##Makefile##s mit hunderten von Zielen-es ist bei FreeBSD praktisch möglich, das gesamte Betriebssystem zu kompilieren, indem man nur `make world` im richtigen Verzeichnis eingibt! Eine weitere nützliche Eigenschaft der makefiles ist, daß die Ziele keine Programme sein müssen. Wir könnten zum Beispiel eine make Datei haben, die wie folgt aussieht: [.programlisting] .... foo: foo.c cc -o foo foo.c install: cp foo /home/me .... Wir können make sagen welches Ziel wir erzeugt haben wollen, indem wir etwas wie folgt eingeben: [source,shell] .... % make target .... `make` wird dann nur dieses Ziel beachten und alle anderen ignorieren. Wenn wir zum Beispiel `make foo` mit dem obigen makefile eingeben, dann wird make das Ziel `install` ignorieren. Wenn wir nur `make` eingeben wird make immer nur nach dem ersten Ziel suchen und danach mit dem Suchen aufhören. Wenn wir hier also nur `make` eingegeben hätten, würde es nur zu dem Ziel `foo` gehen, gegebenenfalls [.filename]#foo# neu kompilieren, und danach einfach aufhören, ohne das Ziel `install` zu beachten. Beachten Sie, daß das `install`-Ziel von nichts anderem abhängt! Dies bedeutet, daß der Befehl in der nachfolgenden Zeile immer ausgeführt wird, wenn wir dieses Ziel mittels `make install` aufrufen. In diesem Fall wird die Datei [.filename]#foo# in das Heimatverzeichnis des Benutzers kopiert. Diese Vorgehensweise wird häufig bei makefiles von Anwendungen benutzt, damit die Anwendung nach erfolgreicher Kompilierung in das richtige Verzeichnis installiert werden kann. Dieser Teil ist etwas schwierig zu erklären. Wenn Sie immer noch nicht so richtig verstanden haben, wie `make` funktioniert, wäre es das Beste, sie erstellen sich selber ein einfaches Programm wie "hello world" und eine make Datei wie die weiter oben angegebene, und experimentieren damit selber ein bißchen herum. Als nächstes könnten Sie mehrere Quelltextdateien verwenden, oder in Ihrer Quelltextdatei eine Header-Datei includen. Der Befehl `touch` ist an dieser Stelle ganz hilfreich-er verändert das Datum einer Datei, ohne das Sie diese extra editieren müssen. === Make und include-Dateien C-Code beginnt häufig mit einer Liste von Dateien, die included werden sollen, zum Beispiel stdio.h. Manche dieser Dateien sind include-Dateien des Systems, andere gehören zum aktuellen Projekt, an dem Sie gerade arbeiten: [.programlisting] .... #include #include "foo.h" int main(.... .... Um sicherzustellen, daß diese Datei neu kompiliert wird, wenn [.filename]#foo.h# verändert wurde, müssen Sie diese Datei Ihrem [.filename]#Makefile# hinzufügen: [.programlisting] .... foo: foo.c foo.h .... Sobald Ihr Projekt größer wird und Sie mehr und mehr eigene include-Dateien verwalten müssen wird es nur noch sehr schwer möglich sein, die Übersicht über alle include-Dateien und Dateien, die von diesen abhängen, beizubehalten. Falls Sie eine include-Datei verändern, jedoch das erneute Kompilieren aller Dateien, die von dieser Datei abhängen, vergessen, werden die Folgen verheerend sein. Der `gcc` besitzt eine Option, bei der er Ihre Dateien analysiert und eine Liste aller include-Dateien und deren Abhängigkeiten erstellt: `-MM`. Wenn Sie das Folgende zu Ihrem Makefile hinzufügen: [.programlisting] .... depend: gcc -E -MM *.c > .depend .... und `make depend` ausführen, wird die Datei [.filename]#.depend# mit einer Liste von Objekt-Dateien, C-Dateien und den include-Dateien auftauchen: [.programlisting] .... foo.o: foo.c foo.h .... Falls Sie [.filename]#foo.h# verändern werden beim nächsten Aufruf von `make` alle Dateien, die von [.filename]#foo.h# abhängen, neu kompiliert. Vergessen Sie nicht jedes mal `make depend` aufzurufen, wenn Sie eine include-Datei zu einer Ihrer Dateien hinzugefügt haben. === FreeBSD Makefiles Makefiles können eher schwierig zu schreiben sein. Glücklicherweise kommen BSD-basierende Systeme wie FreeBSD mit einigen sehr mächtigen solcher Dateien als Teil des Systems daher. Ein sehr gutes Beispiel dafür ist das FreeBSD Portssystem. Hier ist der grundlegende Teil eines typischen [.filename]##Makefile##s des Portssystems: [.programlisting] .... MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include .... Wenn wir jetzt in das Verzeichnis dieses Ports wechseln und `make` aufrufen, passiert das Folgende: [.procedure] ==== . Es wird überprüft, ob sich der Quelltext für diesen Port bereits auf Ihrem System befindet. . Falls dies nicht der Fall ist wird eine FTP-Verbindung zu der URL in MASTER_SITES aufgebaut und der Quelltext heruntergeladen. . Die Checksumme für den Quelltext wird berechnet und mit der schon bekannten und für sicher und gut empfundenen verglichen. Damit wird sichergestellt, daß der Quelltext bei der Übertragung nicht beschädigt wurde. . Sämtliche Anpassungen, die nötig sind, damit der Quelltext unter FreeBSD funktioniert, werden vorgenommen-dieser Vorgang wird auch _patchen_ genannt. . Alle speziellen Konfigurationen, die am Quelltext nötig sind, werden vorgenommen. (Viele UNIX(R) Programmdistributionen versuchen herauszufinden, auf welcher UNIX(R)-Version sie kompiliert werden sollen und welche optionalen UNIX(R)-Features vorhanden sind-an dieser Stelle erhalten sie die Informationen im FreeBSD Ports Szenario). . Der Quelltext für das Programm wird kompiliert. Im Endeffekt wechseln wir in das Verzeichnis, in das der Quelltext entpackt wurde, und rufen `make` auf-die eigene make-Datei des Programms besitzt die nötigen Informationen um dieses zu bauen. . Wir haben jetzt eine kompilierte Version des Programmes. Wenn wir wollen können wir dieses jetzt testen; wenn wir überzeugt vom Programm sind, können wir `make install` eingeben. Dadurch werden das Programm sowie alle zugehörigen Dateien an die richtige Stelle kopiert; es wird auch ein Eintrag in der `Paketdatenbank` erzeugt, sodaß der Port sehr einfach wieder deinstalliert werden kann, falls wir unsere Meinung über dieses geändert haben. ==== Ich glaube jetzt werden Sie mit mir übereinstimmen, daß dies ziemlich eindrucksvoll für ein Skript mit vier Zeilen ist! Das Geheimnis liegt in der letzten Zeile, die `make` anweist, in das makefile des Systems mit dem Namen [.filename]#bsd.port.mk# zu sehen. Man kann diese Zeile zwar leicht übersehen, aber hierher kommt all das klevere Zeugs-jemand hat ein makefile geschrieben, welches `make` anweist, alle weiter oben beschriebenen Schritte durchzuführen (neben vielen weiteren Dingen, die ich nicht angesprochen habe, einschließlich der Behandlung sämtlicher Fehler, die auftreten könnten) und jeder kann darauf zurückgreifen, indem er eine einzige Zeile in seine eigene make-Datei einfügt! Falls Sie einen Blick in die makefiles des Systems werfen möchten, finden Sie diese in [.filename]#/usr/shared/mk#. Es ist aber wahrscheinlich besser, wenn Sie damit noch warten, bis Sie ein bißchen mehr Praxiserfahrung mit makefiles gesammelt haben, da die dortigen makefiles sehr kompliziert sind (und wenn Sie sich diese ansehen sollten Sie besser eine Kanne starken Kaffee griffbereit haben!) === Fortgeschrittene Verwendung von `make` `Make` ist ein sehr mächtiges Werkzeug und kann noch sehr viel mehr als die gezeigten einfachen Beispiele weiter oben. Bedauerlicherweise gibt es mehrere verschiedene Versionen von `make`, und sie alle unterscheiden sich beträchtlich voneinander. Der beste Weg herauszufinden was sie können ist wahrscheinlich deren Dokumentation zu lesen-hoffentlich hat diese Einführung Ihnen genügend Grundkenntnisse vermitteln können, damit Sie dies tun können. Die Version von make, die in FreeBSD enthalten ist, ist Berkeley make; es gibt eine Anleitung dazu in [.filename]#/usr/shared/doc/psd/12.make#. Um sich diese anzusehen, müssen Sie [source,shell] .... % zmore paper.ascii.gz .... in diesem Verzeichnis ausführen. Viele Anwendungen in den Ports verwenden GNU make, welches einen sehr guten Satz an "info"-Seiten mitbringt. Falls Sie irgendeinen dieser Ports installiert haben wurde GNU make automatisch als `gmake` mit installiert. Es ist auch als eigenständiger Port und Paket verfügbar. Um sich die Info-Seiten für GNU make anzusehen müssen Sie die Datei [.filename]#dir# in [.filename]#/usr/local/info# um einen entsprechenden Eintrag erweitern. Dies beinhaltet das Einfügen einer Zeile wie [.programlisting] .... * Make: (make). The GNU Make utility. .... in die Datei. Nachdem Sie dies getan haben können Sie `info` eingeben und dann den Menüeintrag [.guimenuitem]#make# auswählen (oder Sie können in Emacs die Tastenkombination `C-h i` verwenden). [[debugging]] == Debuggen === Der Debugger Der Debugger bei FreeBSD heißt `gdb` (GNU debugger). Sie können Ihn durch die Eingabe von [source,shell] .... % gdb progname .... starten, wobei viele Leute ihn vorzugsweise innerhalb von Emacs aufrufen. Sie erreichen dies durch die Eingabe von: [source,shell] .... M-x gdb RET progname RET .... Die Verwendung eines Debuggers erlaubt Ihnen Ihr Programm unter kontrollierteren Bedingungen ausführen zu können. Typischerweise können Sie so Zeile für Zeile durch Ihr Programm gehen, die Werte von Variablen untersuchen, diese verändern, dem Debugger sagen er soll das Programm bis zu einem bestimmten Punkt ausführen und dann anhalten, und so weiter und so fort. Sie können damit sogar ein schon laufendes Programm untersuchen, oder eine Datei mit einem Kernspeicherabbild laden um herauszufinden, warum das Programm abgestürzt ist. Es ist sogar möglich damit den Kernel zu debuggen, wobei dies etwas trickreicher als bei den Benutzeranwendungen ist, welche wir in diesem Abschnitt behandeln werden. Der `gdb` besitzt eine recht gute Online-Hilfe, sowie einen Satz von Info-Seiten, weshalb sich dieser Abschnitt auf ein paar grundlegende Befehle beschränken wird. Falls Sie den textbasierten Kommandozeilen-Stil abstoßend finden gibt es ein graphisches Front-End dafür (package:devel/xxgdb[]) in der Ports-Sammlung. Dieser Abschnitt ist als Einführung in die Verwendung des `gdb` gedacht und beinhaltet nicht spezielle Themen wie das Debuggen des Kernels. === Ein Programm im Debugger ausführen Sie müssen das Programm mit der Option `-g` kompiliert haben um den `gdb` effektiv einsetzen zu können. Es geht auch ohne diese Option, allerdings werden Sie dann nur den Namen der Funktion sehen, in der Sie sich gerade befinden, anstatt direkt den zugehörigen Quelltext. Falls Sie eine Meldung wie die folgende sehen: [source,shell] .... … (no debugging symbols found) … .... wenn der `gdb` gestartet wird, dann wissen Sie, daß das Programm nicht mit der Option `-g` kompiliert wurde. Geben Sie in der Eingabeaufforderung des `gdb break main` ein. Dies weist den Debugger an, dass Sie nicht daran interessiert sind, den einleitenden Schritten beim Programmstart zuzusehen und dass am Anfang Ihres Codes die Ausführung beginnen soll. Geben Sie nun `run` ein, um das Programm zu starten - es wird starten und beim Aufruf von `main()` vom Debugger angehalten werden. (Falls Sie sich jemals gewundert haben von welcher Stelle `main()` aufgerufen wird, dann wissen Sie es jetzt!). Sie können nun Schritt für Schritt durch Ihr Programm gehen, indem Sie `n` drücken. Wenn Sie zu einem Funktionsaufruf kommen können Sie diese Funktion durch drücken von `s` betreten. Sobald Sie sich in einem Funktionsaufruf befinden können Sie diesen durch drücken von `f` wieder verlassen. Sie können auch `up` und `down` verwenden, um sich schnell den Aufrufer einer Funktion anzusehen. Hier ist ein einfaches Beispiel, wie man mit Hilfe des `gdb` einen Fehler in einem Programm findet. Dies ist unser eigenes Programm (mit einem absichtlich eingebauten Fehler): [.programlisting] .... #include 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; } .... Dieses Programm setzt i auf den Wert `5` und übergibt dies einer Funktion `bazz()`, welche den Wert ausgibt, den Sie von uns erhalten hat. Wenn wir das Programm kompilieren und ausführen erhalten wir [source,shell] .... % cc -g -o temp temp.c % ./temp This is my program anint = 4231 .... Das ist nicht was wir erwartet hatten! Es ist Zeit, daß wir sehen was hier passiert! [source,shell] .... % 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) .... Halt mal! Wieso hat denn anint den Wert `4231`? Haben wir dieser Variablen nicht in `main()` den Wert `5` zugewiesen? Gehen wir mal zurück zu `main()` und schauen dort nach. [source,shell] .... (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! Anscheinend haben wir vergessen i zu initialisieren. Wir wollten eigentlich [.programlisting] .... ... main() { int i; i = 5; printf("This is my program\n"); ... .... schreiben, haben aber die Zeile mit `i=5;` vergessen. Da wir i nicht initialisiert haben hatte diese Variable gerade den Wert, der in dem ihr zugewiesenen Speicherbereich stand als wir das Programm gestartet haben, welcher in diesem Fall `4231` war. [NOTE] ==== Der `gdb` zeigt jedes mal, wenn wir eine Funktion betreten oder verlassen, den Inhalt des Stack-Rahmens an, selbst wenn wir uns mit `up` und `down` im Aufruf-Stack umher bewegen. Dabei wird der Name der Funktion sowie der übergebenen Argumente angezeigt, was uns dabei hilft, die Übersicht zu behalten. (Der Stack ist ein Speicherbereich, in dem ein Programm Informationen über die an eine Funktion übergebenen Argumente ablegt, sowie die Rücksprungadresse eines Funktionsaufrufes). ==== === Eine Kernspeicherdatei untersuchen Eine Kernspeicherdatei ist im Prinzip eine Datei, die den vollständigen Zustand eines Prozesses enthält, als dieses abgestürzt ist. In "den guten alten Zeiten" mußten Programmierer hexadezimale Listen der Kernspeicherdatei ausdrucken und über Maschinencodehandbüchern schwitzen, aber heutzutage ist das Leben etwas einfacher geworden. Zufälligerweise wird die Kernspeicherdatei unter FreeBSD und anderen 4.4BSD-Systemen [.filename]#progname.core# anstatt einfach nur [.filename]#core# genannt, um deutlich zu machen, zu welchem Programm eine Kernspeicherdatei gehört. Um eine Kernspeicherdatei zu untersuchen müssen Sie den `gdb` wie gewohnt starten. An Stelle von `break` oder `run` müssen Sie das Folgende eingeben [source,shell] .... (gdb) core progname.core .... Wenn Sie sich nicht in demselben Verzeichnis befinden wie die Kernspeicherdatei müssen Sie zuerst `dir /path/to/core/file` eingeben. Sie sollten dann etwas wie folgt sehen: [source,shell] .... % 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 diesem Fall hieß das Programm [.filename]#a.out#, weshalb die Kernspeicherdatei den Namen [.filename]#a.out.core# trägt. Wie wir sehen können stürzte das Programm in einer Funktion namens `bazz` ab, als es versuchte auf einen Speicherbereich zuzugreifen, der dem Programm nicht zur Verfügung stand. Manchmal ist es ganz nützlich zu sehen, wie eine Funktion aufgerufen wurde, da bei komplexen Programmen das eigentliche Problem schon sehr viel weiter oben auf dem Aufruf-Stack aufgetreten sein könnte. Der Befehl `bt` veranlaßt den `gdb` dazu, einen Backtrace des Aufruf-Stacks auszugeben: [source,shell] .... (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) .... Die Funktion `end()` wird aufgerufen, wenn ein Programm abstürzt; in diesem Fall wurde die Funktion `bazz()` aus der `main()`-Funktion heraus aufgerufen. === Ein bereits laufendes Programm untersuchen Eine der tollsten Features des `gdb` ist die Möglichkeit, damit bereits laufende Programme zu untersuchen. Dies bedeutet natürlich, daß Sie die erforderlichen Rechte dafür besitzen. Ein häufig auftretendes Problem ist das Untersuchen eines Programmes, welches sich selber forkt. Vielleicht will man den Kindprozess untersuchen, aber der Debugger erlaubt einem nur den Zugriff auf den Elternprozess. Was Sie an solch einer Stelle machen ist, Sie starten einen weiteren `gdb`, ermitteln mit Hilfe von `ps` die Prozess-ID des Kindprozesses, und geben [source,shell] .... (gdb) attach pid .... im `gdb` ein, und können dann wie üblich mit der Fehlersuche fortfahren. "Das ist zwar alles sehr schön," werden Sie jetzt vielleicht denken, "aber in der Zeit, in der ich diese Schritte durchführe, ist der Kindprozess schon längst über alle Berge". Fürchtet euch nicht, edler Leser, denn Ihr müßt wie folgt vorgehen (freundlicherweise zur Verfügung gestellt von den Info-Seite des `gdb`): [source,shell] .... … 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 */ … } else { /* parent */ … .... Alles was Sie jetzt noch tun müssen ist, sich an den Kindprozess ranzuhängen, PauseMode auf `0` zu setzen und auf den `sleep()` Funktionsaufruf zu warten, um zurückzukehren! [[emacs]] == Emacs als Entwicklungsumgebung verwenden === Emacs Leider werden UNIX(R)-Systeme nicht mit einem alles-was-du-jemals-brauchst-und-vieles-mehr-megapaket an integrierten Entwicklungsumgebungen ausgestattet, die bei anderen Systemen dabei sind. Trotzdem ist es möglich, seine eigene Entwicklungsumgebung aufzusetzen. Diese wird vielleicht nicht so hübsch und integriert sein, aber dafür können Sie sie Ihren eigenen Wünschen anpassen. Und sie ist frei. Und Sie haben die Quelltexte davon. Der Schlüssel zu all dem ist Emacs. Es gibt zwar ein paar Leute die ihn hassen, es gibt jedoch auch viele die ihn lieben. Falls Sie zu ersteren gehören befürchte ich, daß dieser Abschnitt Ihnen wenig interessantes zu bieten hat. Des weiteren benötigen Sie eine angemessene Menge an freiem Speicher, um ihn zu benutzen-ich würde 8MB für den Textmodus und 16MB unter X als absolutes Minimum empfehlen, um eine halbwegs brauchbare Performance zu erhalten. Emacs ist im Prinzip ein extrem anpassbarer Editor- in der Tat ist er so stark veränderbar, daß er eher einem Betriebssystem als einem Editor gleicht! Viele Entwickler und Systemadministratoren erledigen praktisch ihre gesamte Arbeit aus Emacs heraus und beenden ihn nur, um sich komplett auszuloggen. Es ist nicht einmal möglich alles hier zusammenzufassen, was man mit dem Emacs machen kann. Im Folgenden werden einige Features aufgelistet, die für einen Entwickler interessant sein könnten: * Sehr mächtiger Editor, der suchen-und-ersetzen mit Zeichenfolgen und regulären Ausdrücken (Pattern) sowie das direkte Anspringen von Anfang/Ende von Blockausdrücken erlaubt, etc, etc. * Pull-Down Menüs und eine Online-Hilfe. * Sprachunabhängige Syntaxhervorhebung und automatische Einrückung. * Vollständig konfigurierbar. * Sie können Programme im Emacs kompilieren und debuggen. * Bei Kompilationsfehlern können Sie direkt zu der entsprechenden Zeile im Quelltext springen. * Benutzerfreundliches Front-End für das `info`-Programm, um die GNU Hypertext Dokumentation inklusive der Dokumentation des Emacs selber. * Benutzerfreundliches Front-End für den `gdb` um sich beim Verfolgen der Programmanweisungen den zugehörigen Quelltext anzeigen zu lassen. * Sie können E-Mails und News im Usenet lesen, während ihr Programm kompiliert wird. Und zweifelsfrei viele weitere Punkte, die ich übersehen habe. Emacs kann unter FreeBSD über den package:editors/emacs[] Port installiert werden. Sobald er installiert ist starten Sie ihn, und geben dann `C-h t` ein, um die Einführung in Emacs zu lesen-d.h. Sie sollen bei gedrückter kbd:[Strg]-Taste die kbd:[h]-Taste drücken, beide wieder loslassen und anschließend kbd:[t] drücken. (Alternativ können Sie mit der Maus den Eintrag [.guimenuitem]#Emacs Tutorial# aus dem menu:Hilfe[]-Menü auswählen). Obwohl der Emacs Menüs besitzt ist das Erlernen der Tastaturkombinationen lohnenswert, da man beim Editieren sehr viel schneller Tastenkombinationen eingeben kann, als die Maus zu finden und mit dieser dann an der richtigen Stelle zu klicken. Und wenn Sie sich mit erfahrenen Emacs-Benutzern unterhalten werden Sie feststellen, daß diese häufig nebenbei Ausdrücke wie "`M-x replace-s RET foo RET bar RET`" verwenden, weshalb das Erlernen dieser sehr nützlich ist. Und Emacs hat auf jeden Fall weit mehr nützliche Funktionen als das diese in der Menüleiste unterzubringen wären. Zum Glück ist es sehr einfach die jeweiligen Tastaturkombinationen herauszubekommen, da diese direkt neben den Menüeinträgen stehen. Meine Empfehlung wäre, den Menüeintrag für, sagen wir, das Öffnen einer Datei zu verwenden, bis Sie die Funktionsweise verstanden haben und sie mit dieser vertraut sind, und es dann mit C-x C-f versuchen. Wenn Sie damit zufrieden sind, gehen Sie zum nächsten Menüeintrag. Falls Sie sich nicht daran erinnern können, was eine bestimmte Tastenkombination macht, wählen Sie [.guimenuitem]#Describe Key# aus dem menu:Hilfe[]-Menü aus und geben Sie die Tastenkombination ein-Emacs sagt Ihnen dann was diese macht. Sie können ebenfalls den Menüeintrag [.guimenuitem]#Command Apropos# verwenden, um alle Befehle, die ein bestimmtes Wort enthalten, mit den zugehörigen Tastenkombinationen aufgelistet zu bekommen. Übrigends bedeutet der Ausdruck weiter oben, bei gedrückter kbd:[Meta]-Taste kbd:[x] zu drücken, beide wieder loszulassen, `replace-s` einzugeben (Kurzversion für `replace-string`-ein weiteres Feature des Emacs ist, daß Sie Befehle abkürzen können), anschließend die kbd:[return]-Taste zu drücken, dann `foo` einzugeben (die Zeichenkette, die Sie ersetzen möchten), dann wieder kbd:[return], dann die Leertaste zu drücken (die Zeichenkette, mit der Sie `foo` ersetzen möchten) und anschließend erneut kbd:[return] zu drücken. Emacs wird dann die gewünschte suchen-und-ersetzen-Operation ausführen. Wenn Sie sich fragen was in aller Welt die kbd:[Meta]-Taste ist, das ist eine spezielle Taste die viele UNIX(R)-Workstations besitzen. Bedauerlicherweise haben PCs keine solche Taste, und daher ist es üblicherweise die kbd:[alt]-Taste (oder falls Sie Pech haben die kbd:[Esc]-Taste). Oh, und um den Emacs zu verlassen müssen sie `C-x C-c` (das bedeutet, Sie müssen bei gedrückter kbd:[Strg]-Taste zuerst kbd:[x] und dann kbd:[c] drücken) eingeben. Falls Sie noch irgendwelche ungespeicherten Dateien offen haben wird Emacs Sie fragen ob Sie diese speichern wollen. (Ignorieren Sie bitte die Stelle der Dokumentation, an der gesagt wird, daß `C-z` der übliche Weg ist, Emacs zu verlassen-dadurch wird der Emacs in den Hintergrund geschaltet, was nur nützlich ist, wenn Sie an einem System ohne virtuelle Terminals arbeiten). === Emacs konfigurieren Emacs kann viele wundervolle Dinge; manche dieser Dinge sind schon eingebaut, andere müssen erst konfiguriert werden. Anstelle einer proprietären Macrosprache verwendet der Emacs für die Konfiguration eine speziell für Editoren angepaßte Version von Lisp, auch bekannt als Emacs Lisp. Das Arbeiten mit Emacs Lisp kann sehr hilfreich sein, wenn Sie darauf aufbauend etwas wie Common Lisp lernen möchten. Emacs Lisp hat viele Features von Common Lisp obwohl es beträchtlich kleiner ist (und daher auch einfacher zu beherrschen). Der beste Weg um Emacs Lisp zu erlernen besteht darin, sich das link:ftp://ftp.gnu.org/old-gnu/emacs/elisp-manual-19-2.4.tar.gz[Emacs Tutorial] herunterzuladen. Es ist jedoch keine Kenntnis von Lisp erforderlich, um mit der Konfiguration von Emacs zu beginnen, da ich eine beispielhafte [.filename]#.emacs#-Datei hier eingefügt habe, die für den Anfang ausreichen sollte. Kopieren Sie diese einfach in Ihr Heimverzeichnis und starten Sie den Emacs neu, falls dieser bereits läuft; er wird die Befehle aus der Datei lesen und Ihnen (hoffentlich) eine brauchbare Grundeinstellung bieten. === Eine beispielhafte [.filename]#.emacs#-Datei Bedauerlicherweise gibt es hier viel zu viel, um es im Detail zu erklären; es gibt jedoch ein oder zwei Punkte, die besonders erwähnenswert sind. * Alles was mit einem `;` anfängt ist ein Kommentar und wird von Emacs ignoriert. * In der ersten Zeile mit `-*- Emacs-Lisp -*-` sorgt dafür, daß wir die Datei [.filename]#.emacs# in Emacs selber editieren können und uns damit alle tollen Features zum Editieren von Emacs Lisp zur Verfügung stehen. Emacs versucht dies normalerweise anhand des Dateinamens auszumachen, was vielleicht bei [.filename]#.emacs# nicht funktionieren könnte. * Die kbd:[Tab]-Taste ist in manchen Modi an die Einrückungsfunktion gebunden, so daß beim drücken dieser Taste die aktuelle Zeile eingerückt wird. Wenn Sie ein tab-Zeichen in einen Text, welchen auch immer Sie dabei schreiben, einfügen wollen, müssen Sie bei gedrückter kbd:[Strg]-Taste die kbd:[Tab]-Taste drücken. * Diese Datei unterstützt Syntax Highlighting für C, C++, Perl, Lisp und Scheme, indem die Sprache anhand des Dateinamens erraten wird. * Emacs hat bereits eine vordefinierte Funktion mit dem Namen `next-error`. Diese erlaubt es einem, in einem Fenster mit der Kompilierungsausgabe mittels `M-n` von einem zum nächsten Kompilierungsfehler zu springen; wir definieren eine komplementäre Funktion `previous-error`, die es uns erlaubt, mittels `M-p` von einem zum vorherigen Kompilierungsfehler zu springen. Das schönste Feature von allen ist, daß mittels `C-c C-c` die Quelltextdatei, in der der Fehler aufgetreten ist, geöffnet und die betreffende Zeile direkt angesprungen wird. * Wir aktivieren die Möglichkeit von Emacs als Server zu agieren, so daß wenn Sie etwas außerhalb von Emacs machen und eine Datei editieren möchten, Sie einfach das folgende eingeben können + [source,shell] .... % emacsclient filename .... + und dann die Datei in Ihrem Emacs editieren können! .Eine einfache [.filename]#.emacs#-Datei [example] ==== [.programlisting] .... ;; -*-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 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) (if (>= emacs-major-version 21) (setq show-trailing-whitespace t)) ;; 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 color &optional bold) "Create a face from a color and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face color) (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) ".") .... ==== === Erweitern des von Emacs unterstützten Sprachbereichs Das ist jetzt alles sehr schön wenn Sie ausschließlich in einer der Sprachen programmieren wollen, um die wir uns bereits in der [.filename]#.emacs#-Datei gekümmert haben (C, C++, Perl, Lisp und Scheme), aber was passiert wenn eine neue Sprache namens "whizbang" herauskommt, mit jeder Menge neuen tollen Features? Als erstes muß festgestellt werden, ob whizbang mit irgendwelchen Dateien daherkommt, die Emacs etwas über die Sprache sagen. Diese enden üblicherweise auf [.filename]#.el#, der Kurzform für "Emacs Lisp". Falls whizbang zum Beispiel ein FreeBSD Port ist, könnten wir diese Dateien mittels [source,shell] .... % find /usr/ports/lang/whizbang -name "*.el" -print .... finden und durch Kopieren in das Emacs-seitige Lisp-Verzeichnis installieren. Unter FreeBSD ist dies [.filename]#/usr/local/shared/emacs/site-lisp#. Wenn zum Beispiel die Ausgabe des find-Befehls wie folgt war [source,shell] .... /usr/ports/lang/whizbang/work/misc/whizbang.el .... könnten wir das folgende tun [source,shell] .... # cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/shared/emacs/site-lisp .... Als nächstes müssen wir festlegen, welche Dateiendung Quelltextdateien für whizbang haben. Lassen Sie uns um der Argumente Willen annehmen, die Dateiendung sei [.filename]#.wiz#. Wir müssen dann einen Eintrag unserer [.filename]#.emacs#-Datei hinzufügen um sicherzustellen, daß Emacs die Informationen in [.filename]#whizbang.el# auch verwenden kann. Suchen Sie den auto-mode-alist Eintrag in der [.filename]#.emacs#-Datei und fügen Sie an dieser Stelle eine Zeile wie folgt für whizbang hinzu: [.programlisting] .... ... ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) ... .... Dies bedeutet das Emacs automatisch in den `whizbang-mode` wechseln wird, wenn Sie eine Datei mit der Dateiendung [.filename]#.wiz# editieren. Direkt darunter werden Sie den Eintrag font-lock-auto-mode-list finden. Erweitern Sie den `whizbang-mode` um diesen wie folgt: [.programlisting] .... ;; 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") .... Dies bedeutet das Emacs immer `font-lock-mode` (z.B. Syntax Highlighting) aktiviert, wenn Sie eine [.filename]#.wiz#-Datei editieren. Und das ist alles was benötigt wird. Falls es weitere Dinge gibt, die automatisch beim Öffnen einer [.filename]#.wiz#-Datei ausgeführt werden sollen, können Sie einen `whizbang-mode hook`-Eintrag hinzufügen (für ein einfaches Beispiel, welches `auto-indent` hinzufügt, sehen Sie sich bitte `my-scheme-mode-hook` an). [[tools-reading]] == Weiterführende Literatur Für Informationen zum Aufsetzen einer Entwicklungsumgebung, um Fehlerbehebungen an FreeBSD selber beizusteuern sehen Sie sich bitte man:development[7] an. * 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/documentation/content/en/books/developers-handbook/tools/_index.adoc b/documentation/content/en/books/developers-handbook/tools/_index.adoc index eedd83a25a..c1dbec7094 100644 --- a/documentation/content/en/books/developers-handbook/tools/_index.adoc +++ b/documentation/content/en/books/developers-handbook/tools/_index.adoc @@ -1,1641 +1,1641 @@ --- title: Chapter 2. Programming Tools authors: - author: James Raynard - author: Murray Stokely prev: books/developers-handbook/introduction next: books/developers-handbook/secure description: Programming Tools tags: ["tools", "Interpreters", "Compilers", "cc", "make", "Debugging", "lldb", "gdb", "clang", "Emacs"] showBookMenu: true weight: 3 path: "/books/developers-handbook/tools/" --- [[tools]] = Programming Tools :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 2 :partnums: :source-highlighter: rouge :experimental: :c-plus-plus-command: c++ :clang-plus-plus-command: clang++ :images-path: books/developers-handbook/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[tools-synopsis]] == Synopsis This chapter 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(R). It does _not_ attempt to describe coding in any detail. Most of the chapter assumes little or no previous programming knowledge, although it is hoped that most programmers will find something of value in it. [[tools-intro]] == Introduction FreeBSD offers an excellent development environment. Compilers for C and C++ and an assembler come with the basic system, not to mention classic UNIX(R) tools such as `sed` and `awk`. If that is not enough, there are many more compilers and interpreters in the Ports collection. The following section, <>, lists some of the available options. FreeBSD is very compatible with standards such as POSIX(R) 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 have never written programs on a UNIX(R) 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(R) and a willingness to learn! [[tools-programming]] == 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(R) 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(R) 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 from the FreeBSD Ports Collection, with a brief discussion of some of the more popular interpreted languages. Instructions on how to get and install applications from the Ports Collection can be found in the extref:{handbook}[Ports section, ports-using] of the handbook. 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 is also the foundation for Visual Basic. + The Bywater Basic Interpreter can be found in the Ports Collection as package:lang/bwbasic[] and the Phil Cockroft's Basic Interpreter (formerly Rabbit Basic) is available as package:lang/pbasic[]. 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". It is very popular in AI (Artificial Intelligence) circles. + Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. + Various implementations of Lisp that can run on UNIX(R) systems are available in the Ports Collection for FreeBSD. GNU Common Lisp can be found as package:lang/gcl[]. CLISP by Bruno Haible and Michael Stoll is available as package:lang/clisp[]. For CMUCL, which includes a highly-optimizing compiler too, or simpler Lisp implementations like SLisp, which implements most of the Common Lisp constructs in a few hundred lines of C code, package:lang/cmucl[] and package:lang/slisp[] are available respectively. Perl:: Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. + Perl is available in the Ports Collection as package:lang/perl5.24[] for all FreeBSD releases. 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. + Scheme is available from the Ports Collection as package:lang/elk[] for the Elk Scheme Interpreter. The MIT Scheme Interpreter can be found in package:lang/mit-scheme[] and the SCM Scheme Interpreter in package:lang/scm[]. Icon:: Icon is a high-level language with extensive facilities for processing strings and structures. The version of Icon for FreeBSD can be found in the Ports Collection as package:lang/icon[]. Logo:: Logo is a language that is easy to learn, and has been used as an introductory programming language in various courses. It is an excellent tool to work with when teaching programming to smaller age groups, as it makes creation of elaborate geometric shapes an easy task. + The latest version of Logo for FreeBSD is available from the Ports Collection in package:lang/logo[]. Python:: Python is an Object-Oriented, interpreted language. Its advocates argue that it is one of the best languages to start programming with, since it is relatively easy to start with, but is not limited in comparison to other popular interpreted languages that are used for the development of large, complex applications (Perl and Tcl are two other languages that are popular for such tasks). + The latest version of Python is available from the Ports Collection in package:lang/python[]. Ruby:: Ruby is an interpreter, pure object-oriented programming language. It has become widely popular because of its easy to understand syntax, flexibility when writing code, and the ability to easily develop and maintain large, complex programs. + Ruby is available from the Ports Collection as package:lang/ruby32[]. Tcl and Tk:: Tcl is an embeddable, interpreted language, that has become widely used and became popular mostly because of its portability to many platforms. It can be used both for quickly writing small, prototype applications, or (when combined with Tk, a GUI toolkit) fully-fledged, featureful programs. + Various versions of Tcl are available as ports for FreeBSD. -The latest version, Tcl 8.5, can be found in package:lang/tcl87[]. +The latest version, Tcl 8.7, can be found in package:lang/tcl87[]. === 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.footnote:[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 is also useful if you need to write very efficient code, as the compiler can take its time and optimize the code, which would not be acceptable in an interpreter. Moreover, 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. 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 include an IDE in the base system, but package:devel/kdevelop[] is available in the Ports Collection and many use Emacs for this purpose. Using Emacs as an IDE is discussed in <>. [[tools-compiling]] == Compiling with `cc` This section deals with the clang compiler for C and C++, as it's installed with the FreeBSD base system. Starting with FreeBSD 10.X `clang` is installed as `cc`; the GNU compiler package:lang/gcc[gcc] is available in the Ports Collection. 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 have 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. [.procedure] . 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. . 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 filesystem. 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 [source,bash] .... % cc foobar.c .... will cause [.filename]#foobar.c# to be compiled by all the steps above. If you have more than one file to compile, just do something like [source,bash] .... % 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.footnote:[In case you did not know, a binary sort is an efficient way of sorting things into order and a bubble sort is not.] There are lots and lots of options for `cc`, which are all in the manual page. Here are a few of the most important ones, with examples of how to use them. `-o _filename_`:: The output name of the file. If you do not use this option, `cc` will produce an executable called [.filename]#a.out#.footnote:[The reasons for this are buried in the mists of history.] + [source,bash] .... % cc foobar.c executable is a.out % cc -o foobar foobar.c executable is foobar .... `-c`:: 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 [.filename]#Makefile#. + [source,bash] .... % cc -c foobar.c .... + This will produce an _object file_ (not an executable) called [.filename]#foobar.o#. This can be linked together with other object files into an executable. `-g`:: 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 `-g` while you are developing a program and then compile a "release version" without `-g` when you are satisfied it works properly. + [source,bash] .... % cc -g foobar.c .... + This will produce a debug version of the program. footnote:[Note, we did not use the -o 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!] `-O`:: Create an optimized version of the executable. The compiler performs various clever tricks to try to produce an executable that runs faster than normal. You can add a number after the `-O` to specify a higher level of optimization, but this often exposes bugs in the compiler's optimizer. + [source,bash] .... % cc -O -o foobar foobar.c .... + This will produce an optimized version of [.filename]#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. `-Wall`:: 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. `-ansi`:: 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. `-pedantic`:: 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 rewrite the program later to get it to work somewhere else - and who knows what you may be using in a few years time? [source,bash] .... % cc -Wall -ansi -pedantic -o foobar foobar.c .... This will produce an executable [.filename]#foobar# after checking [.filename]#foobar.c# for standard compliance. `-l__library__`:: Specify a function library to be used at link time. + 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 [.filename]#libsomething.a#, you give `cc` the argument `-l__something__`. For example, the math library is [.filename]#libm.a#, so you give `cc` the argument `-lm`. A common "gotcha" with the math library is that it has to be the last library on the command line. + [source,bash] .... % cc -o foobar foobar.c -lm .... + This will link the math library functions into [.filename]#foobar#. + If you are compiling C++ code, use {c-plus-plus-command}. {c-plus-plus-command} can also be invoked as {clang-plus-plus-command} on FreeBSD. + [source,bash] .... % c++ -o foobar foobar.cc .... + This will both produce an executable [.filename]#foobar# from the C++ source file [.filename]#foobar.cc#. === Common `cc` Queries and Problems ==== I compiled a file called foobar.c and I cannot find an executable called foobar. Where has it gone? Remember, `cc` will call the executable [.filename]#a.out# unless you tell it differently. Use the `-o _filename_` option: [source,bash] .... % cc -o foobar foobar.c .... ==== 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? Unlike MS-DOS(R), UNIX(R) 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. Type `./foobar`, which means "run the file called [.filename]#foobar# in the current directory." === I called my executable test, but nothing happens when I run it. What is going on? Most UNIX(R) systems have a program called `test` in [.filename]#/usr/bin# and the shell is picking that one up before it gets to checking the current directory. Either type: [source,bash] .... % ./test .... or choose a better name for your program! ==== 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? The name _core dump_ dates back to the very early days of UNIX(R), 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 [.filename]#core#, which the programmer could then pore over to find out what went wrong. ==== Fascinating stuff, but what I am supposed to do now? Use a debugger to analyze the core (see <>). ==== When my program dumped core, it said something about a segmentation fault. What is that? This basically means that your program tried to perform some sort of illegal operation on memory; UNIX(R) 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 + [.programlisting] .... char *foo = NULL; strcpy(foo, "bang!"); .... * Using a pointer that has not been initialized, eg + [.programlisting] .... char *foo; strcpy(foo, "bang!"); .... + The pointer will have some random value that, with luck, will point into an area of memory that is not available to your program and the kernel will kill your program before it can do any damage. If you are unlucky, it will 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 + [.programlisting] .... int bar[20]; bar[27] = 6; .... * Trying to store something in read-only memory, eg + [.programlisting] .... char *foo = "My string"; strcpy(foo, "bang!"); .... + UNIX(R) compilers often put string literals like `"My string"` into read-only areas of memory. * Doing naughty things with `malloc()` and `free()`, eg + [.programlisting] .... char bar[80]; free(bar); .... + or + [.programlisting] .... 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 run well on one system can crash when you try them on another. ==== Sometimes when I get a core dump it says bus error. It says in my UNIX(R) book that this means a hardware problem, but the computer still seems to be working. Is this true? 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 should not have. ==== 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 is an error? Yes, just go to another console or xterm, do [source,bash] .... % ps .... to find out the process ID of your program, and do [source,bash] .... % 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. Alternatively, you can create a core dump from inside your program, by calling the `abort()` function. See the manual page of man:abort[3] to learn more. If you want to create a core dump from outside your program, but do not want the process to terminate, you can use the `gcore` program. See the manual page of man:gcore[1] for more information. [[tools-make]] == Make === What is `make`? When you are working on a simple program with only one or two source files, typing in [source,bash] .... % 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: [source,bash] .... % cc file1.o file2.o … file37.c … .... if we had changed [.filename]#file37.c#, but not any of the others, since the last time we compiled. This may speed up the compilation quite a bit, but does not 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 are working in a team with other people who forget to tell us when they have 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 is 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 do not. For example, a rule could say something like "if [.filename]#fromboz.o# is older than [.filename]#fromboz.c#, that means someone must have changed [.filename]#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 [.filename]#makefile#, [.filename]#Makefile# or [.filename]#MAKEFILE#. Most programmers use the name [.filename]#Makefile#, as this puts it near the top of a directory listing, where it can easily be seen.footnote:[They do not use the MAKEFILE form as block capitals are often used for documentation files like README.] === Example of Using `make` Here is a very simple make file: [.programlisting] .... 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 [.filename]#foo# exists; if it exists, it compares the time [.filename]#foo# was last modified to the time [.filename]#foo.c# was last modified. If [.filename]#foo# does not exist, or is older than [.filename]#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 [.filename]#foo.c# needs to be re-compiled. The creation line starts with a tab (press kbd:[tab]) and then the command you would type to create [.filename]#foo# if you were doing it at a command prompt. If [.filename]#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 [.filename]#foo.c#. So, when you type `make`, it will make sure that [.filename]#foo# is up to date with respect to your latest changes to [.filename]#foo.c#. This principle can be extended to [.filename]#Makefile#'s 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 do not have to be programs. For instance, we could have a make file that looks like this: [.programlisting] .... 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: [source,bash] .... % 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 [.filename]#foo# if necessary, and then stop without going on to the `install` target. Notice that the `install` target does not 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 [.filename]#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 to explain. If you do not 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. `touch` is very useful here-it changes the date on a file without you having to edit it. === Make and include-files C code often starts with a list of files to include, for example stdio.h. Some of these files are system-include files, some of them are from the project you are now working on: [.programlisting] .... #include #include "foo.h" int main(.... .... To make sure that this file is recompiled the moment [.filename]#foo.h# is changed, you have to add it in your [.filename]#Makefile#: [.programlisting] .... foo: foo.c foo.h .... The moment your project is getting bigger and you have more and more own include-files to maintain, it will be a pain to keep track of all include files and the files which are depending on it. If you change an include-file but forget to recompile all the files which are depending on it, the results will be devastating. `clang` has an option to analyze your files and to produce a list of include-files and their dependencies: `-MM`. If you add this to your Makefile: [.programlisting] .... depend: cc -E -MM *.c > .depend .... and run `make depend`, the file [.filename]#.depend# will appear with a list of object-files, C-files and the include-files: [.programlisting] .... foo.o: foo.c foo.h .... If you change [.filename]#foo.h#, next time you run `make` all files depending on [.filename]#foo.h# will be recompiled. Do not forget to run `make depend` each time you add an include-file to one of your files. === 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 is the essential part of a typical ports [.filename]#Makefile#: [.programlisting] .... MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include .... Now, if we go to the directory for this port and type `make`, the following happens: [.procedure] . A check is made to see if the source code for this port is already on the system. . If it is not, 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(R) program distributions try to work out which version of UNIX(R) they are being compiled on and which optional UNIX(R) 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 will agree that is rather impressive for a four line script! The secret lies in the last line, which tells `make` to look in the system makefile called [.filename]#bsd.port.mk#. It is 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 did not 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 are in [.filename]#/usr/share/mk#, but it is probably best to wait until you have 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 `make` `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 man:make[1] manual page offers a comprehensive discussion of variables, arguments, and how to use make. 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 is also available as a port and package in its own right. To view the info pages for GNU make, you will have to edit [.filename]#dir# in the [.filename]#/usr/local/info# directory to add an entry for it. This involves adding a line like [.programlisting] .... * Make: (make). The GNU Make utility. .... to the file. Once you have done this, you can type `info` and then select [.guimenuitem]#make# from the menu (or in Emacs, do `C-h i`). [[debugging]] == Debugging === Introduction to Available Debuggers Using a debugger allows running the program under more controlled circumstances. Typically, it is possible to 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. It is also possible to attach to a program that is already running, or load a core file to investigate why the program crashed. This section is intended to be a quick introduction to using debuggers and does not cover specialized topics such as debugging the kernel. For more information about that, refer to crossref:kerneldebug[kerneldebug,Kernel Debugging]. The standard debugger supplied with FreeBSD is called `lldb` (LLVM debugger). As it is part of the standard installation for that release, there is no need to do anything special to use it. It has good command help, accessible via the `help` command, as well as https://lldb.llvm.org/[a web tutorial and documentation]. [NOTE] ==== The `lldb` command is also available extref:{handbook}ports/[from ports or packages, ports-using] as package:devel/llvm[]. ==== The other debugger available with FreeBSD is called `gdb` (GNU debugger). Unlike lldb, it is not installed by default on FreeBSD; to use it, extref:{handbook}#ports-using/[install] package:devel/gdb[] from ports or packages. It has excellent on-line help, as well as a set of info pages. The two debuggers have a similar feature set, so which one to use is largely a matter of taste. If familiar with one only, use that one. People familiar with neither or both but wanting to use one from inside Emacs will need to use `gdb` as `lldb` is unsupported by Emacs. Otherwise, try both and see which one you prefer. === Using lldb ==== Starting lldb Start up lldb by typing [source,bash] .... % lldb -- progname .... ==== Running a Program with lldb Compile the program with `-g` to get the most out of using `lldb`. It will work without, but will only display the name of the function currently running, instead of the source code. If it displays a line like: [source,bash] .... Breakpoint 1: where = temp`main, address = … .... (without an indication of source code filename and line number) when setting a breakpoint, this means that the program was not compiled with `-g`. [TIP] ==== Most `lldb` commands have shorter forms that can be used instead. The longer forms are used here for clarity. ==== At the `lldb` prompt, type `breakpoint set -n main`. This will tell the debugger not to display the preliminary set-up code in the program being run and to stop execution at the beginning of the program's code. Now type `process launch` to actually 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()`. To step through the program a line at a time, type `thread step-over`. When the program gets to a function call, step into it by typing `thread step-in`. Once in a function call, return from it by typing `thread step-out` or use `up` and `down` to take a quick look at the caller. Here is a simple example of how to spot a mistake in a program with `lldb`. This is our program (with a deliberate mistake): [.programlisting] .... #include 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. Compiling and running the program displays [source,bash] .... % cc -g -o temp temp.c % ./temp This is my program anint = -5360 .... That is not what was expected! Time to see what is going on! [source,bash] .... % lldb -- temp (lldb) target create "temp" Current executable set to 'temp' (x86_64). (lldb) breakpoint set -n main Skip the set-up code Breakpoint 1: where = temp`main + 15 at temp.c:8:2, address = 0x00000000002012ef lldb puts breakpoint at main() (lldb) process launch Run as far as main() Process 9992 launching Process 9992 launched: '/home/pauamma/tmp/temp' (x86_64) Program starts running Process 9992 stopped * thread #1, name = 'temp', stop reason = breakpoint 1.1 lldb stops at main() frame #0: 0x00000000002012ef temp`main at temp.c:8:2 5 main() { 6 int i; 7 -> 8 printf("This is my program\n"); Indicates the line where it stopped 9 bazz(i); 10 return 0; 11 } (lldb) thread step-over Go to next line This is my program Program prints out Process 9992 stopped * thread #1, name = 'temp', stop reason = step over frame #0: 0x0000000000201300 temp`main at temp.c:9:7 6 int i; 7 8 printf("This is my program\n"); -> 9 bazz(i); 10 return 0; 11 } 12 (lldb) thread step-in step into bazz() Process 9992 stopped * thread #1, name = 'temp', stop reason = step in frame #0: 0x000000000020132b temp`bazz(anint=-5360) at temp.c:14:29 lldb displays stack frame 11 } 12 13 int bazz(int anint) { -> 14 printf("You gave me %d\n", anint); 15 return anint; 16 } (lldb) .... Hang on a minute! How did anint get to be `-5360`? Was it not set to `5` in `main()`? Let us move up to `main()` and have a look. [source,bash] .... (lldb) up Move up call stack frame #1: 0x000000000020130b temp`main at temp.c:9:2 lldb displays stack frame 6 int i; 7 8 printf("This is my program\n"); -> 9 bazz(i); 10 return 0; 11 } 12 (lldb) frame variable i Show us the value of i (int) i = -5360 lldb displays -5360 .... Oh dear! Looking at the code, we forgot to initialize i. We meant to put [.programlisting] .... ... main() { int i; i = 5; printf("This is my program\n"); ... .... but we left the `i=5;` line out. As we did not initialize i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be `-5360`. [NOTE] ==== The `lldb` command displays the stack frame every time we go into or out of a function, even if we are 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 is 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 with lldb 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 [.filename]#progname.core# instead of just [.filename]#core#, to make it clearer which program a core file belongs to. To examine a core file, specify the name of the core file in addition to the program itself. Instead of starting up `lldb` in the usual way, type `lldb -c _progname_.core \-- _progname_`. The debugger will display something like this: [source,bash,subs="verbatim,quotes"] .... % lldb -c [.filename]#progname.core# -- [.filename]#progname# (lldb) target create "[.filename]#progname#" --core "[.filename]#progname#.core" Core file '/home/pauamma/tmp/[.filename]#progname.core#' (x86_64) was loaded. (lldb) .... In this case, the program was called [.filename]#progname#, so the core file is called [.filename]#progname.core#. The debugger does not display why the program crashed or where. For this, use `thread backtrace all`. This will also show how the function where the program dumped core was called. [source,bash,subs="verbatim,quotes"] .... (lldb) thread backtrace all * thread #1, name = 'progname', stop reason = signal SIGSEGV * frame #0: 0x0000000000201347 progname`bazz(anint=5) at temp2.c:17:10 frame #1: 0x0000000000201312 progname`main at temp2.c:10:2 frame #2: 0x000000000020110f progname`_start(ap=, cleanup=) at crt1.c:76:7 (lldb) .... `SIGSEGV` indicates that the program tried to access memory (run code or read/write data usually) at a location that does not belong to it, but does not give any specifics. For that, look at the source code at line 10 of file temp2.c, in `bazz()`. The backtrace also says that in this case, `bazz()` was called from `main()`. ==== Attaching to a Running Program with lldb One of the neatest features about `lldb` is that it can attach to a program that is already running. Of course, that requires sufficient permissions to do so. A common problem is stepping through a program that forks and wanting to trace the child, but the debugger will only trace the parent. To do that, start up another `lldb`, use `ps` to find the process ID for the child, and do [source,bash] .... (lldb) process attach -p pid .... in `lldb`, and then debug as usual. For that to work well, the code that calls `fork` to create the child needs to do something like the following (courtesy of the `gdb` info pages): [.programlisting] .... ... 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 */ ... } else { /* parent */ ... .... Now all that is needed is to attach to the child, set PauseMode to `0` with `expr PauseMode = 0` and wait for the `sleep()` call to return. === Remote Debugging Using LLDB [NOTE] ==== The described functionality is available starting with LLDB version 12.0.0. Users of FreeBSD releases containing an earlier LLDB version may wish to use the snapshot available in extref:{handbook}[ports or packages, ports-using], as package:devel/llvm-devel[]. ==== Starting with LLDB 12.0.0, remote debugging is supported on FreeBSD. This means that `lldb-server` can be started to debug a program on one host, while the interactive `lldb` client connects to it from another one. To launch a new process to be debugged remotely, run `lldb-server` on the remote server by typing [source,bash] .... % lldb-server g host:port -- progname .... The process will be stopped immediately after launching, and `lldb-server` will wait for the client to connect. Start `lldb` locally and type the following command to connect to the remote server: [source,bash] .... (lldb) gdb-remote host:port .... `lldb-server` can also attach to a running process. To do that, type the following on the remote server: [source,bash] .... % lldb-server g host:port --attach pid-or-name .... === Using gdb ==== Starting gdb Start up gdb by typing [source,bash] .... % gdb progname .... although many people prefer to run it inside Emacs. To do this, type: [source,bash] .... M-x gdb RET progname RET .... Finally, for those finding its text-based command-prompt style off-putting, there is a graphical front-end for it (package:devel/xxgdb[]) in the Ports Collection. ==== Running a Program with gdb Compile the program with `-g` to get the most out of using `gdb`. It will work without, but will only display the name of the function currently running, instead of the source code. A line like: [source,bash] .... ... (no debugging symbols found) ... .... when `gdb` starts up means that the program was not compiled with `-g`. At the `gdb` prompt, type `break main`. This will tell the debugger to skip the preliminary set-up code in the program being run and to stop execution at the beginning of the program's 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()`. To step through the program a line at a time, press `n`. When at a function call, step into it by pressing `s`. Once in a function call, return from it by pressing `f`, or use `up` and `down` to take a quick look at the caller. Here is a simple example of how to spot a mistake in a program with `gdb`. This is our program (with a deliberate mistake): [.programlisting] .... #include 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. Compiling and running the program displays [source,bash] .... % cc -g -o temp temp.c % ./temp This is my program anint = 4231 .... That was not what we expected! Time to see what is going on! [source,bash] .... % 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`? Was it not set to `5` in `main()`? Let us move up to `main()` and have a look. [source,bash] .... (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 initialize i. We meant to put [.programlisting] .... ... main() { int i; i = 5; printf("This is my program\n"); ... .... but we left the `i=5;` line out. As we did not initialize 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`. [NOTE] ==== The `gdb` command displays the stack frame every time we go into or out of a function, even if we are 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 is 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 with gdb 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 [.filename]#progname.core# instead of just [.filename]#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 [source,bash] .... (gdb) core progname.core .... If the core file is not in the current directory, type `dir /path/to/core/file` first. The debugger should display something like this: [source,bash,subs="verbatim,quotes"] .... % gdb [.filename]#progname# 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 [.filename]#progname.core# Core was generated by `[.filename]#progname#'. 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 [.filename]#progname#, so the core file is called [.filename]#progname.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 is 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. `bt` causes `gdb` to print out a back-trace of the call stack: [source,bash] .... (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 with gdb One of the neatest features about `gdb` is that it can attach to a program that is already running. Of course, that requires sufficient permissions to do so. A common problem is stepping through a program that forks and wanting to trace the child, but the debugger will only trace the parent. To do that, start up another `gdb`, use `ps` to find the process ID for the child, and do [source,bash] .... (gdb) attach pid .... in `gdb`, and then debug as usual. For that to work well, the code that calls `fork` to create the child needs to do something like the following (courtesy of the `gdb` info pages): [.programlisting] .... ... 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 */ ... } else { /* parent */ ... .... Now all that is needed is to attach to the child, set PauseMode to `0`, and wait for the `sleep()` call to return! [[emacs]] == Using Emacs as a Development Environment === Emacs Emacs is a highly customizable editor-indeed, it has been customized to the point where it is 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 is impossible even to summarize 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 customizable. * 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. And doubtless many more that have been overlooked. Emacs can be installed on FreeBSD using the package:editors/emacs[] port. Once it is installed, start it up and do `C-h t` to read an Emacs tutorial-that means hold down kbd:[control], press kbd:[h], let go of kbd:[control], and then press kbd:[t]. (Alternatively, you can use the mouse to select [.guimenuitem]#Emacs Tutorial# from the menu:Help[] menu.) Although Emacs does have menus, it is well worth learning the key bindings, as it is much quicker when you are editing something to press a couple of keys than to try to find the mouse and then click on the right place. And, when you are talking to seasoned Emacs users, you will find they often casually throw around expressions like "`M-x replace-s RET foo RET bar RET`" so it is 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 is quite easy to pick up the key-bindings, as they are 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 are happy with that, move on to another menu command. If you cannot remember what a particular combination of keys does, select [.guimenuitem]#Describe Key# from the menu:Help[] menu and type it in-Emacs will tell you what it does. You can also use the [.guimenuitem]#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 kbd:[Meta] key, press kbd:[x], release the kbd:[Meta] key, type `replace-s` (short for `replace-string`-another feature of Emacs is that you can abbreviate commands), press the kbd:[return] key, type `foo` (the string you want replaced), press the kbd:[return] key, type bar (the string you want to replace `foo` with) and press kbd:[return] again. Emacs will then do the search-and-replace operation you have just requested. If you are wondering what on earth kbd:[Meta] is, it is a special key that many UNIX(R) workstations have. Unfortunately, PC's do not have one, so it is usually kbd:[alt] (or if you are unlucky, the kbd:[escape] key). Oh, and to get out of Emacs, do `C-x C-c` (that means hold down the kbd:[control] key, press kbd:[x], press kbd:[c] and release the kbd:[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 are on a system which does not 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. Working with Emacs Lisp can be quite helpful if you want to go on and learn something like Common Lisp. Emacs Lisp has many features of Common Lisp, although it is considerably smaller (and thus easier to master). The best way to learn Emacs Lisp is to read the online link:https://www.gnu.org/software/emacs/manual/elisp.html[Emacs Reference] manual. However, there is no need to actually know any Lisp to get started with configuring Emacs, as I have included a sample [.filename]#.emacs#, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it is already running; it will read the commands from the file and (hopefully) give you a useful basic setup. === A Sample [.filename]#.emacs# Unfortunately, there is 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 [.filename]#.emacs# 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 [.filename]#.emacs#. * The kbd:[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 are writing, hold the kbd:[control] key down while you are pressing the kbd:[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 are doing something outside Emacs and you want to edit a file, you can just type in + [source,bash] .... % emacsclient filename .... + and then you can edit the file in your Emacs!footnote:[Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit a file.] .A Sample [.filename]#.emacs# ==== [.programlisting] .... ;; -*-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 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) (if (>= emacs-major-version 21) (setq show-trailing-whitespace t)) ;; 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 color &optional bold) "Create a face from a color and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face color) (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 [.filename]#.emacs# (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 [.filename]#.el#, short for "Emacs Lisp". For example, if whizbang is a FreeBSD port, we can locate these files by doing [source,bash] .... % find /usr/ports/lang/whizbang -name "*.el" -print .... and install them by copying them into the Emacs site Lisp directory. On FreeBSD, this is [.filename]#/usr/local/share/emacs/site-lisp#. So for example, if the output from the find command was [source,bash] .... /usr/ports/lang/whizbang/work/misc/whizbang.el .... we would do [source,bash] .... # 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 us say for the sake of argument that they all end in [.filename]#.wiz#. We need to add an entry to our [.filename]#.emacs# to make sure Emacs will be able to use the information in [.filename]#whizbang.el#. Find the auto-mode-alist entry in [.filename]#.emacs# and add a line for whizbang, such as: [.programlisting] .... ... ("\\.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 [.filename]#.wiz#. Just below this, you will find the font-lock-auto-mode-list entry. Add `whizbang-mode` to it like so: [.programlisting] .... ;; 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 [.filename]#.wiz# file. And that is all that is needed. If there is anything else you want done automatically when you open up [.filename]#.wiz#, you can add a `whizbang-mode hook` (see `my-scheme-mode-hook` for a simple example that adds `auto-indent`). [[tools-reading]] == Further Reading For information about setting up a development environment for contributing fixes to FreeBSD itself, please see man:development[7]. * 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