Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 95

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 95 страницаB. Stroustrup - The C++ Programming Language (794319) страница 952019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 95)

*/ };class Token { /* ... */ };class Token_stream { /* ... */ };extern Token_stream is;}In addition to lexer.h, the implementation of the lexer depends on error.h and on the character-classification functions in <cctype> (§36.2):// lexer.cpp:#include "lexer.h"#include "error.h"#include <iostream>#include <cctype>// redundant: in lexer.hLexer::Token_stream is; // defaults to ‘‘read from cin’’Lexer::Token Lexer::Token_stream::get() { /* ... */ };Lexer::Token& Lexer::Token_stream::current() { /* ...

*/ };We could have factored out the #include directive forconsidered that excessive for this tiny program.error.has theLexer’s _impl.hfile. However, ISection 15.3.2.1Other Calculator Modules439As usual, we #include the interface offered by the module – in this case, lexer.h – in the module’s implementation to give the compiler a chance to check consistency.The symbol table is essentially self-contained, although the standard-library header <map>could drag in all kinds of interesting stuff to implement an efficient map template class:// table.h:#include <map>#include <string>namespace Table {extern std::map<std::string,double> table;}Because we assume that every header may bedeclaration of table from its definition:#includedin several.cppfiles, we must separate the// table.cpp:#include "table.h"std::map<std::string,double> Table::table;I just stuck the driver into main.cpp:// main.cpp:#include "parser.h"#include "lexer.h" // to be able to set ts#include "error.h"#include "table.h" // to be able to predefine names#include <sstream> // to be able to put main()’s arguments into a string streamnamespace Driver {void calculate() { /* ...

*/ }}int main(int argc, char∗ argv[]) { /* ... */ }For a larger system, it is usually worthwhile to separate out the driver and minimize what is done inmain(). That way main() calls a driver function placed in a separate source file. This is particularlyimportant for code intended to be used as a library. Then, we cannot rely on code in main() andmust be prepared for the driver to be called from a variety of functions.15.3.2.2 Use of HeadersThe number of headers to use for a program is a function of many factors.

Many of these factorshave more to do with the way files are handled on your system than with C++. For example, ifyour editor/IDE does not make it convenient to look at several files simultaneously, then usingmany headers becomes less attractive.440Source Files and ProgramsChapter 15A word of caution: a few dozen headers plus the standard headers for the program’s executionenvironment (which can often be counted in the hundreds) are usually manageable.

However, ifyou partition the declarations of a large program into the logically minimal-size headers (puttingeach structure declaration in its own file, etc.), you can easily get an unmanageable mess of hundreds of files even for minor projects. I find that excessive.For large projects, multiple headers are unavoidable. In such projects, hundreds of files (notcounting standard headers) are the norm. The real confusion starts when they begin to be countedin the thousands. At that scale, the basic techniques discussed here still apply, but their management becomes a Herculean task.

Tools, such as dependency analysers, can be of great help, butthere is little they can do for compiler and linker performance if the program is an unstructuredmess. Remember that for realistically sized programs, the single-header style is not an option.Such programs will have multiple headers. The choice between the two styles of organizationoccurs (repeatedly) for the parts that make up the program.The single-header style and the multiple-header style are not really alternatives. They are complementary techniques that must be considered whenever a significant module is designed and mustbe reconsidered as a system evolves.

It’s crucial to remember that one interface doesn’t serve allequally well. It is usually worthwhile to distinguish between the implementers’ interface and theusers’ interface. In addition, many larger systems are structured so that providing a simple interface for the majority of users and a more extensive interface for expert users is a good idea. Theexpert users’ interfaces (‘‘complete interfaces’’) tend to #include many more features than the average user would ever want to know about. In fact, the average users’ interface can often be identified by eliminating features that require the inclusion of headers that define facilities that would beunknown to the average user. The term ‘‘average user’’ is not derogatory.

In the fields in which Idon’t have to be an expert, I strongly prefer to be an average user. In that way, I minimize hassles.15.3.3 Include GuardsThe idea of the multiple-header approach is to represent each logical module as a consistent, selfcontained unit. Viewed from the program as a whole, many of the declarations needed to makeeach logical module complete are redundant. For larger programs, such redundancy can lead toerrors, as a header containing class definitions or inline functions gets #included twice in the samecompilation unit (§15.2.3).We have two choices. We can[1] reorganize our program to remove the redundancy, or[2] find a way to allow repeated inclusion of headers.The first approach – which led to the final version of the calculator – is tedious and impractical forrealistically sized programs.

We also need that redundancy to make the individual parts of the program comprehensible in isolation.The benefits of an analysis of redundant #includes and the resulting simplifications of the program can be significant both from a logical point of view and by reducing compile times. However,it can rarely be complete, so some method of allowing redundant #includes must be applied.

Preferably, it must be applied systematically, since there is no way of knowing how thorough an analysisa user will find worthwhile.Section 15.3.3Include Guards441The traditional solution is to insert include guards in headers. For example:// error.h:#ifndef CALC_ERROR_H#define CALC_ERROR_Hnamespace Error {// ...}#endif// CALC_ERROR_HThe contents of the file between the #ifndef and #endif are ignored by the compiler ifCALC_ERROR_H is defined.

Thus, the first time error.h is seen during a compilation, its contents areread and CALC_ERROR_H is given a value. Should the compiler be presented with error.h again during the compilation, the contents are ignored. This is a piece of macro hackery, but it works and itis pervasive in the C and C++ worlds. The standard headers all have include guards.Header files are included in essentially arbitrary contexts, and there is no namespace protectionagainst macro name clashes. Consequently, I choose rather long and ugly names for my includeguards.Once people get used to headers and include guards, they tend to include lots of headers directlyand indirectly. Even with C++ implementations that optimize the processing of headers, this can beundesirable. It can cause unnecessarily long compile time, and it can bring lots of declarations andmacros into scope.

The latter might affect the meaning of the program in unpredictable andadverse ways. Headers should be included only when necessary.15.4 ProgramsA program is a collection of separately compiled units combined by a linker. Every function,object, type, etc., used in this collection must have a unique definition (§6.3, §15.2.3).

A programmust contain exactly one function called main() (§2.2.1). The main computation performed by theprogram starts with the invocation of the global function main() and ends with a return from main().The return type of main() is int, and the following two versions of main() are supported by all implementations:int main() { /* ... */ }int main(int argc, char∗ argv[]) { /* ... */ }A program can only provide one of those two alternatives.

In addition, an implementation canallow other versions of main(). The argc, argv version is used to transmit arguments from the program’s environment; see §10.2.7.The int returned by main() is passed to whatever system invoked main() as the result of the program. A nonzero return value from main() indicates an error.This simple story must be elaborated on for programs that contain global variables (§15.4.1) orthat throw an uncaught exception (§13.5.2.5).442Source Files and ProgramsChapter 1515.4.1 Initialization of Nonlocal VariablesIn principle, a variable defined outside any function (that is, global, namespace, and class staticvariables) is initialized before main() is invoked.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6401
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее