Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 5

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 5 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 52018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

See theappendix for more information.The Program: HelloTextHere’s the program we’re going to build. It’s your first example of SymbianOS C++ source code:// hellotext.cpp#include <e32base.h>#include <e32cons.h>LOCAL_D CConsoleBase* gConsole;// Real main functionvoid MainL(){gConsole->Printf(_L("Hello world!\n"));}// Console harnessvoid ConsoleMainL(){// Get a consolegConsole = Console::NewL(_L("Hello Text"),TSize(KConsFullScreen, KConsFullScreen));CleanupStack::PushL(gConsole);// Call functionMainL();// Pause before terminatingUser::After(5000000); // 5 second delay// Finished with consoleCleanupStack::PopAndDestroy(gConsole);}// Cleanup stack harnessGLDEF_C TInt E32Main(){__UHEAP_MARK;CTrapCleanup* cleanupStack = CTrapCleanup::New();TRAPD(error, ConsoleMainL());__ASSERT_ALWAYS(!error, User::Panic(_L("Hello world panic"), error));delete cleanupStack;__UHEAP_MARKEND;return 0;}8GETTING STARTEDOur main purpose here is to understand the Symbian OS tool chain,but while we have the opportunity, there are a few things to observe inthe source code above.

There are three functions:• the actual ‘Hello world!’ work is done in MainL()• ConsoleMainL() allocates a console and calls MainL()• E32Main() allocates a trap harness and then calls ConsoleMainL().On first sight, this looks odd. Why have three functions to do whatmost programming systems can achieve in a single line? The answer issimple: real programs, even small ones, aren’t one-liners.

So there’s nopoint in optimizing the system design to deliver a short, sub-minimalprogram. Instead, Symbian OS is optimized to meet the concerns ofreal-world programs – in particular, to handle and recover from memoryallocation failures with minimal programming overhead. There’s a secondreason why this example is longer than you might expect: real programson a user-friendly machine use a GUI framework rather than a rawconsole environment.

If we want a console, we have to construct itourselves, along with the error-handling framework that the GUI wouldhave included for us.Error handling is of fundamental importance in a machine with limitedmemory and disk resources, such as those for which Symbian OS wasdesigned. Errors are going to happen and you can’t afford not to handlethem properly. We’ll explain the error-handling framework and its terminology, such as trap harness, cleanup stack, leave and heap marking, inChapter 4.The Symbian OS error-handling framework is easy to use, so theoverheads for the programmer are minimal.

You might doubt that, judgingby this example! After you’ve seen more realistic examples, you’ll havebetter grounds for making a proper judgement.Back to HelloText. The real work is done in MainL():// Real main functionvoid MainL(){gConsole->Printf(_L("Hello world!\n"));}The printf() that you would expect to find in a C ‘Hello World’ program has become Console>Printf() here. That’s because SymbianOS is object-oriented: Printf() is a member of the CConsoleBaseclass.The _L macro turns a C-style string into a Symbian OS-style descriptor.We’ll find out more about descriptors, and a better alternative to the _Lmacro, in Chapter 5.HELLO WORLD – TEXT VERSION9Symbian OS always starts text programs with the E32Main() function.E32Main() and ConsoleMainL() build two pieces of infrastructureneeded by MainL(): a cleanup stack and a console. Our code forE32Main() is:// Cleanup stack harnessGLDEF_C TInt E32Main(){__UHEAP_MARK;CTrapCleanup* cleanupStack = CTrapCleanup::New();TRAPD(error, ConsoleMainL());__ASSERT_ALWAYS(!error, User::Panic(_L("Hello world panic"), error));delete cleanupStack;__UHEAP_MARKEND;return 0;}The declaration of E32Main() indicates that it is a global function.The GLDEF_C macro, which in practice is only used in this context,is defined as an empty macro in e32def.h.

By marking a functionGLDEF_C, you show that you have thought about it being exported fromthe object module. E32Main() returns a TInt integer. We could haveused int instead of TInt, but since C++ compilers don’t guaranteethat int is a 32-bit signed integer, Symbian OS uses typedefs forstandard types to guarantee they are the same across all Symbian OSimplementations and compilers.E32Main() sets up the error-handling framework.

It sets up a cleanupstack and then calls ConsoleMainL() under a trap harness. The trapharness catches errors – more precisely, it catches any functions thatleave. If you’re familiar with exception handling in standard C++ or Java,TRAP() is like try and catch all in one, User::Leave() is likethrow, and a function with L at the end of its name is like a functionwith throws in its prototype.Here’s ConsoleMainL():// Console harnessvoid ConsoleMainL(){// Get a consolegConsole = Console::NewL(_L("Hello Text"),TSize(KConsFullScreen, KConsFullScreen));CleanupStack::PushL(gConsole);// Call functionMainL();// Pause before terminatingUser::After(15000000); // 15 second delay// Finished with consoleCleanupStack::PopAndDestroy(gConsole);}10GETTING STARTEDThis function allocates a console before calling MainL() to do thePrintf() of the ‘Hello world!’ message.

After that, it briefly pauses andthen deletes the console again.If we were creating this example for a target machine that had akeyboard, we could have replaced the delay code:// Pause before terminatingUser::After(15000000); // 15 second delaywith something like:// Wait for keyconsole->Printf(_L("[ press any key ]"));console->Getch();// Get and ignore characterso that the application would wait for a keypress before terminating.There is no need to trap the call to MainL(), because a leave wouldbe handled by the TRAP() in E32Main().The main purpose of the cleanup stack is to prevent memory leakswhen a leave occurs.

It does this by popping and destroying any objectthat has been pushed to it. So if MainL() leaves, the cleanup stack willensure that the console is popped and destroyed. If MainL() doesn’tleave, then the final statement in ConsoleMainL() will pop and destroyit anyway.In fact, in this particular example MainL() cannot leave, so the Lisn’t theoretically necessary.

But this example is intended to be a startingpoint for other console-mode programs, including programs that do leave.We’ve left the L there to remind you that it’s acceptable for such programsto leave if necessary.If you’re curious, you can browse the headers: e32base.h contains some basic classes used in most Symbian OS programs, whilee32cons.h is used for a console interface and therefore for text-modeprograms – it wouldn’t be necessary for GUI programs.

You can findthese headers (along with the headers for all Symbian OS APIs) in\epoc32\include on your SDK installation drive.The Project Specification FileAs in all C++ development under Symbian OS, we start by building theproject to run under the emulator (that is, for an x86 instruction set)using the Carbide.c++ compiler. We use a debug build so that we cansee the symbolic debug information and to get access to some usefulmemory-leak checking tools. In Chapter 9 we’ll build the project for atarget Symbian OS phone, using an ARM instruction set. At that stagewe’ll use the release build, since that is what you would eventually do tocreate your final, usable, application.HELLO WORLD – TEXT VERSION11For demonstration purposes we’re actually going to build the projecttwice, because you can either compile the code from the command lineor build it in the Carbide.c++ IDE.Each type of build requires a different project file.

To simplify matters, you put all the required information into a single generic projectspecification file, and then use the supplied tools to translate that fileinto the makefiles or project files for one or more of the possible buildenvironments. Project specification files have a .mmp extension (whichstands for ‘makmake project’).

The one for the HelloText project is asfollows:// hellotext.mmpTARGETHelloText.exeTARGETTYPEexeSOURCEPATH.SOURCEhellotext.cppUSERINCLUDE.SYSTEMINCLUDE \epoc32\includeLIBRARYeuser.libThis is enough information to specify the entire project, enablingconfiguration files to be created for any platform or environment.• The TARGET specifies the executable to be generated and the TARGETTYPE confirms that it is an EXE.• SOURCEPATH specifies the location of the source files for this project.• SOURCE specifies the single source file, hellotext.cpp (in laterprojects, we’ll see that SOURCE can be used to specify multiple sourcefiles).• USERINCLUDE and SYSTEMINCLUDE specify the directories to besearched for user include files (those included with quotes; the SYSTEMINCLUDE path is searched as well) and system include files(those included with angle brackets; only the SYSTEMINCLUDEpath is searched).

All Symbian OS projects should specify \epoc32\include for their SYSTEMINCLUDE path.• LIBRARY specifies libraries to link to – these are the .lib filescorresponding to the shared library DLLs whose functions you will becalling at run time. In the case of this very simple program, all weneed is the E32 user library, euser.lib.The Component Definition FileThe Symbian OS build tools require one further file, the componentdefinition file, to be present. This file always has the name bld.inf andcontains a list of all the project definition files (frequently, there is onlyone) that make up the component. In more complex cases it will usually12GETTING STARTEDcontain further build-related information, but the one for HelloText issimply:// BLD.INFPRJ_MMPFILEShellotext.mmpBuilding from the Command LineOnce you’ve typed in the example code for the three files as listed above,we can begin to compile the application.To start the command-line build, open up a command prompt, changeto your installation drive and go to the source directory containing thecode for this example.

The first stage is to invoke bldmake by typing:bldmake bldfilesAfter a short pause, this command will return. By default, bldmakedoesn’t tell you anything. However, if you check the contents of thedirectory, you’ll notice a new file, abld.bat, that is used to drive theremainder of the build process. You will also find that there is a newdirectory in the \epoc32\build directory tree, containing a number ofgenerated files which relate to the various types of build that the buildtools support.Next, use abld to run the rest of the build by typing:abld build winscw udebThe winscw parameter specifies that we are building for the emulator,using the Carbide.c++ compiler, and the udeb parameter means we areusing a (unicode) debug build.

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

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

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

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