Например TDA7294

Форум РадиоКот • Просмотр темы - Нескольно простых вопросов о программировании AVR на Си.
Форум РадиоКот
Здесь можно немножко помяукать :)

Текущее время: Пт дек 05, 2025 05:27:13

Часовой пояс: UTC + 3 часа


ПРЯМО СЕЙЧАС:



Начать новую тему Ответить на тему  [ Сообщений: 1499 ]     ... , , , 22, , , ...  
Автор Сообщение
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Чт ноя 24, 2016 13:41:07 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
ptr128 писал(а):
К оптимизации описание static приводит только в тех случаях, когда компилятор может сам определить, что функция использует не все регистры, которые обязана сохранять вызывающая программа.


это касается не только static, насколько я вижу это верно для всех функций.


"static часто используется для того, чтобы "скрыть" метод в единице трансляции, т.е. в начале .c файла объявляются static функции и переменные и они будут доступны только в этом файле. Даже объявив где-то точно такой же прототип из другого .c файла не получите доступ к этим функциям. А если не использовать static то по-умолчанию область видимости у функций и переменных глобальная, т.е. объявив в другом .c файле прототип функции можно будет использовать реализацию этой функции из другого файла, где она не объявлена static (либо объявлена extern)."

и все, все остальное домыслы.... :))

зы
все пошел железками заниматься...


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Чт ноя 24, 2016 13:54:12 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 1
WiseLord писал(а):
К тому же и я призываю - выносить в заголовки только нужные фцнкции, а не все подряд.

Проблема в том, что только при классической, из учебников, методологии разработки "сверху-вниз" заранее известно, какие функции будут для каждого файла исходного кода внешними, а какие нет. На практике, это скорее исключение, чем правило. И получается наоборот. Объявляются static только те функции, которые точно локализованы в пределах одного файла, а все остальные остаются внешними. Потому что начинаю писать модуль в одном файле, а в результате их оказывается несколько. И, строго говоря, за весь жизненный цикл программы, не раз еще функция, использованная в одном модуле, станет использоваться в нескольких.

Добавлено after 4 minutes 21 second:
_dark писал(а):
ptr128 писал(а):
К оптимизации описание static приводит только в тех случаях, когда компилятор может сам определить, что функция использует не все регистры, которые обязана сохранять вызывающая программа.


это касается не только static, насколько я вижу это верно для всех функций.


Для других функций компилятор это определить не в состоянии. Потому что какой именно экземпляр функции будет вызван, тот что в текущем файле, или тот, что в другом объектном файле, будет решаться компоновщиком. Например, если Ваш исходный код собрать в библиотеку, а потом скомпоновать с объектным модулем, содержащим функцию с тем же именем, что есть в Вашем библиотечном модуле, то будет вызываться везде функция из нового объектного модуля, а не из Вашей библиотеки.

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Чт ноя 24, 2016 13:59:24 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
ptr128 писал(а):
Проблема в том, что только при классической, из учебников, методологии разработки "сверху-вниз" заранее известно, какие функции будут для каждого файла исходного кода внешними, а какие нет. На практике, это скорее исключение, чем правило. И получается наоборот. Объявляются static только те функции, которые точно локализованы в пределах одного файла, а все остальные остаются внешними. Потому что начинаю писать модуль в одном файле, а в результате их оказывается несколько. И, строго говоря, за весь жизненный цикл программы, не раз еще функция, использованная в одном модуле, станет использоваться в нескольких.


+1

ps
но мне лень столько писать было, и этож думать нужно связно


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Чт ноя 24, 2016 14:11:54 
Друг Кота
Аватар пользователя

Карма: 86
Рейтинг сообщений: 1035
Зарегистрирован: Чт апр 11, 2013 11:19:59
Сообщений: 4892
Откуда: Минск
Рейтинг сообщения: 0
ptr128 писал(а):
Проблема в том, что только при классической, из учебников, методологии разработки "сверху-вниз" заранее известно, какие функции будут для каждого файла исходного кода внешними, а какие нет. На практике, это скорее исключение, чем правило
Согласен на все 100. На этапе отладки удобно почти всё вынести в хидер, а откуда-нибудь из main.c отлаживать. Какое-нибудь классическое sendPacket() => sendByte() => sendBit(). Но когда уже всё работает, полезно убрать всё лишнее из хидера, оставив пользователю только минимально необходимый и достаточный интерфейс доступа к своему коду.


Вернуться наверх
 
Эиком - электронные компоненты и радиодетали
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Чт ноя 24, 2016 14:29:39 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 0
WiseLord писал(а):
Но когда уже всё работает

А это когда-нибудь может произойти? Ну не считая "Hello, world!" :)))
На практике, программа раньше заканчивает свой жизненный путь, чем в ней все работает как надо во всех ситуациях.

Добавлено after 5 minutes 44 seconds:
WiseLord писал(а):
main.c отлаживать. Какое-нибудь классическое sendPacket() => sendByte() => sendBit().

И кстати, раз где-то send, то где-то должен быть receive. Получаем гетерогенную среду, где один и тот же код может компилиться и для МК, и для ПК/Андроид или МК другой архитектуры. И есть прямой смысл нижний уровень держать открытым, так как потом будет не sendByte(), a sendByteWithParityBit()

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 09:36:19 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
WiseLord, при всем моем уважениии,
я не понимаю почему Вы, используя стандартные библиотеки, а в них в свою очередь только несколько функций (остальные в них тоже открыты, т.к. прописаны в .h)
т.е. Вы допускаете правильность такого подхода у разработчиков этих библиотек,
но в своих исходниках Вы часть прототипов функций описываете только в .c (т.е. закрываете их для внешнего использования).

Тут речь не идет о том, что правильно или не правильно, это вопрос больше о философии подхода к написанию кода...
Мне например, просто лениво и я не понимаю зачем мне писать (и потом переписывать в .h) прототипы в .c,
если возможно просто включать в файл .c его .h, а в .h объявлять прототипы.

зы
ИМХО
То что нужно объявлять прототипы, а не думать где (выше/ниже вызова функции) писать тело, обсуждать не имеет смысла,
т.к. работа без прототипа это сродни быдлокодорству, не стоит к этому приучать новичков.
Знать что "так можно" нужно, но делать этого не стоит.

зызы
а как все хорошо начиналось - тема "Несколько простых вопросов...."


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 09:46:12 
Ум, честь и совесть. И скромность.
Аватар пользователя

Карма: 98
Рейтинг сообщений: 2135
Зарегистрирован: Чт дек 28, 2006 08:19:56
Сообщений: 18436
Откуда: Новочеркасск
Рейтинг сообщения: 1
Медали: 2
Получил миской по аватаре (1) Мявтор 3-й степени (1)
_dark писал(а):
я не понимаю почему Вы, используя стандартные библиотеки, а в них в свою очередь только несколько функций (остальные в них тоже открыты, т.к. прописаны в .h)
т.е. Вы допускаете правильность такого подхода у разработчиков этих библиотек,
но в своих исходниках Вы часть прототипов функций описываете только в .c (т.е. закрываете их для внешнего использования).
но это же очевидно!

допустим, sprintf - открытая библиотечная функция, но она наверняка использует кучу вспомогательных функций для распарсивания строк и преобразования/формирования потока вывода - но вы же их не видите! они закрыты, т.к. служат специфичным целям этой библиотеки.

ровно тот же подход и для самописных "библиотек": те функции, которые используются на верхнем уровне, должны быть открыты, а низкоуровневые - кому они нужны? создавать неоптимальный код ради соблюдения каких-то навязанных правил?

_________________
если рассматривать человека снизу, покажется, что мозг у него глубоко в жопе
при взгляде на многих сверху ничего не меняется...

Мой уютный бложик... заходите!


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 10:01:31 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
ARV, для меня не очевидно...
конечно, к готовой библиотеке (скомпилированной) я приложу .h с пользовательским интерфейсом и в нем действительно может не быть части функционала,
но этот .h никакого отношения к моему .h в проекте не имеет, у них разные функции...

зы
ну соглашусь, что ссылка на стандартные библиотеки может не очень удачная :))


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 10:53:49 
Друг Кота
Аватар пользователя

Карма: 86
Рейтинг сообщений: 1035
Зарегистрирован: Чт апр 11, 2013 11:19:59
Сообщений: 4892
Откуда: Минск
Рейтинг сообщения: 0
_dark писал(а):
Мне например, просто лениво и я не понимаю зачем мне писать (и потом переписывать в .h) прототипы в .c, если возможно просто включать в файл .c его .h, а в .h объявлять прототипы.
А так и не нужно делать. В .c файле - только реализации функций, а прототипы - только в .h. Но не вообще всех функций, релизованных в .c, а только тех, которые нужны. То есть, интерфейса данной библиотеки.

Нет необходимости выносить в .h файл вообще всё, т.к. многое - чисто служебное. Скажем, некоторые функции имеют очень похожие куски кода, которые может оказаться целесообразным вынести в служебную функцию. Но нет никакого смысла выносить её прототип в .h файл.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 12:01:05 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 0
ARV писал(а):
sprintf - открытая библиотечная функция, но она наверняка использует кучу вспомогательных функций для распарсивания строк и преобразования/формирования потока вывода - но вы же их не видите! они закрыты,


Не ожидал от Вас. Хотя бы убедились, что Ваша гипотеза верна, прежде чем писать в форум.
Смотрим glibc 2.24
sprintf() вызывает сразу открытую vsprintf(), которая есть макрос, вызывающий __IO_vsprintf(), которая явно не static и открыта.
Переходим потом к _IO_vfprintf(), описанную как
extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict,
_IO_va_list);
Идем в vfprintf.c, где живет сам код парсинга.
И видим вызовы совершенно открытых itoa(), strnlen(), alloca(), malloc(), memset() и т.п.

А статические там только явно локальные функции buffered_vfprintf(), printf_positional(), printf_unknown() и group_number(). Так как три первых, это не более, чем различные варианты printf, то во всем sprintf() видим только одну локальную скрытую функцию group_number()

Больше никто ничего не закрывал.

Добавлено after 25 minutes 40 seconds:
Добавлю все же. В GNU, из-за малой предсказуемости путей развития проектов и их форков, обычно, внутренние функции не делают статическими, а их имена предваряют одним или несколькими подчеркиваниями. С одной стороны, это позволяет логически изолировать внутренние функции. С другой, одним дефайном определить для внутренней функции стандартное имя без подчеркивания и включить ее описание в документацию.

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 12:07:48 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
ptr128 я как не программист всегда поражался количеству вложенности различных функций в библиотеках, зачем такие сложности?
или в таком нагромаждении абстракций есть какой-то сокральный смысл?

Может существуют какие-то общие принципы (правила) построения библиотек?
(По принципу колеса, можно как на телеге сразу на ось, а можно через подшипники, обоймы и пр...)
Если есть по этому вопросу какие-то ресурсы хотелось бы их посмотреть...


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 12:27:34 
Ум, честь и совесть. И скромность.
Аватар пользователя

Карма: 98
Рейтинг сообщений: 2135
Зарегистрирован: Чт дек 28, 2006 08:19:56
Сообщений: 18436
Откуда: Новочеркасск
Рейтинг сообщения: 0
Медали: 2
Получил миской по аватаре (1) Мявтор 3-й степени (1)
ptr128 писал(а):
Не ожидал от Вас.
а чего вы от меня ожидали? я беру заголовок stdio.h из WinAVR, и не вижу в нем открытых функций с двумя подчеркиваниями в начале, как и ряда других - интерфейс показывает только printf и иже с ними.
Спойлер
Код:
/* Copyright (c) 2002, 2005, 2007 Joerg Wunsch
   All rights reserved.

   Portions of documentation Copyright (c) 1990, 1991, 1993
   The Regents of the University of California.

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.

   * Neither the name of the copyright holders nor the names of
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.

  $Id: stdio.h,v 1.29.2.1 2008/02/23 08:59:27 dmix Exp $
*/

#ifndef _STDIO_H_
#define   _STDIO_H_ 1

#ifndef __ASSEMBLER__

#include <inttypes.h>
#include <stdarg.h>

#define __need_NULL
#define __need_size_t
#include <stddef.h>

/** \file */
/** \defgroup avr_stdio <stdio.h>: Standard IO facilities
    \code #include <stdio.h> \endcode

    <h3>Introduction to the Standard IO facilities</h3>

    This file declares the standard IO facilities that are implemented
    in \c avr-libc.  Due to the nature of the underlying hardware,
    only a limited subset of standard IO is implemented.  There is no
    actual file implementation available, so only device IO can be
    performed.  Since there's no operating system, the application
    needs to provide enough details about their devices in order to
    make them usable by the standard IO facilities.

    Due to space constraints, some functionality has not been
    implemented at all (like some of the \c printf conversions that
    have been left out).  Nevertheless, potential users of this
    implementation should be warned: the \c printf and \c scanf families of functions, although
    usually associated with presumably simple things like the
    famous "Hello, world!" program, are actually fairly complex
    which causes their inclusion to eat up a fair amount of code space.
    Also, they are not fast due to the nature of interpreting the
    format string at run-time.  Whenever possible, resorting to the
    (sometimes non-standard) predetermined conversion facilities that are
    offered by avr-libc will usually cost much less in terms of speed
    and code size.

    <h3>Tunable options for code size vs. feature set</h3>

    In order to allow programmers a code size vs. functionality tradeoff,
    the function vfprintf() which is the heart of the printf family can be
    selected in different flavours using linker options.  See the
    documentation of vfprintf() for a detailed description.  The same
    applies to vfscanf() and the \c scanf family of functions.

    <h3>Outline of the chosen API</h3>

    The standard streams \c stdin, \c stdout, and \c stderr are
    provided, but contrary to the C standard, since avr-libc has no
    knowledge about applicable devices, these streams are not already
    pre-initialized at application startup.  Also, since there is no
    notion of "file" whatsoever to avr-libc, there is no function
    \c fopen() that could be used to associate a stream to some device.
    (See \ref stdio_note1 "note 1".)  Instead, the function \c fdevopen()
    is provided to associate a stream to a device, where the device
    needs to provide a function to send a character, to receive a
    character, or both.  There is no differentiation between "text" and
    "binary" streams inside avr-libc.  Character \c \\n is sent
    literally down to the device's \c put() function.  If the device
    requires a carriage return (\c \\r) character to be sent before
    the linefeed, its \c put() routine must implement this (see
    \ref stdio_note2 "note 2").

    As an alternative method to fdevopen(), the macro
    fdev_setup_stream() might be used to setup a user-supplied FILE
    structure.

    It should be noted that the automatic conversion of a newline
    character into a carriage return - newline sequence breaks binary
    transfers.  If binary transfers are desired, no automatic
    conversion should be performed, but instead any string that aims
    to issue a CR-LF sequence must use <tt>"\r\n"</tt> explicitly.

    For convenience, the first call to \c fdevopen() that opens a
    stream for reading will cause the resulting stream to be aliased
    to \c stdin.  Likewise, the first call to \c fdevopen() that opens
    a stream for writing will cause the resulting stream to be aliased
    to both, \c stdout, and \c stderr.  Thus, if the open was done
    with both, read and write intent, all three standard streams will
    be identical.  Note that these aliases are indistinguishable from
    each other, thus calling \c fclose() on such a stream will also
    effectively close all of its aliases (\ref stdio_note3 "note 3").

    It is possible to tie additional user data to a stream, using
    fdev_set_udata().  The backend put and get functions can then
    extract this user data using fdev_get_udata(), and act
    appropriately.  For example, a single put function could be used
    to talk to two different UARTs that way, or the put and get
    functions could keep internal state between calls there.

    <h3>Format strings in flash ROM</h3>

    All the \c printf and \c scanf family functions come in two flavours: the
    standard name, where the format string is expected to be in
    SRAM, as well as a version with the suffix "_P" where the format
    string is expected to reside in the flash ROM.  The macro
    \c PSTR (explained in \ref avr_pgmspace) becomes very handy
    for declaring these format strings.

    \anchor stdio_without_malloc
    <h3>Running stdio without malloc()</h3>

    By default, fdevopen() requires malloc().  As this is often
    not desired in the limited environment of a microcontroller, an
    alternative option is provided to run completely without malloc().

    The macro fdev_setup_stream() is provided to prepare a
    user-supplied FILE buffer for operation with stdio.

    <h4>Example</h4>

    \code
    #include <stdio.h>

    static int uart_putchar(char c, FILE *stream);

    static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
                                             _FDEV_SETUP_WRITE);

    static int
    uart_putchar(char c, FILE *stream)
    {

      if (c == '\n')
        uart_putchar('\r', stream);
      loop_until_bit_is_set(UCSRA, UDRE);
      UDR = c;
      return 0;
    }

    int
    main(void)
    {
      init_uart();
      stdout = &mystdout;
      printf("Hello, world!\n");

      return 0;
    }
    \endcode

    This example uses the initializer form FDEV_SETUP_STREAM() rather
    than the function-like fdev_setup_stream(), so all data
    initialization happens during C start-up.

    If streams initialized that way are no longer needed, they can be
    destroyed by first calling the macro fdev_close(), and then
    destroying the object itself.  No call to fclose() should be
    issued for these streams.  While calling fclose() itself is
    harmless, it will cause an undefined reference to free() and thus
    cause the linker to link the malloc module into the application.

    <h3>Notes</h3>

    \anchor stdio_note1 \par Note 1:
    It might have been possible to implement a device abstraction that
    is compatible with \c fopen() but since this would have required
    to parse a string, and to take all the information needed either
    out of this string, or out of an additional table that would need to be
    provided by the application, this approach was not taken.

    \anchor stdio_note2 \par Note 2:
    This basically follows the Unix approach: if a device such as a
    terminal needs special handling, it is in the domain of the
    terminal device driver to provide this functionality.  Thus, a
    simple function suitable as \c put() for \c fdevopen() that talks
    to a UART interface might look like this:

    \code
    int
    uart_putchar(char c, FILE *stream)
    {

      if (c == '\n')
        uart_putchar('\r');
      loop_until_bit_is_set(UCSRA, UDRE);
      UDR = c;
      return 0;
    }
    \endcode

    \anchor stdio_note3 \par Note 3:
    This implementation has been chosen because the cost of maintaining
    an alias is considerably smaller than the cost of maintaining full
    copies of each stream.  Yet, providing an implementation that offers
    the complete set of standard streams was deemed to be useful.  Not
    only that writing \c printf() instead of <tt>fprintf(mystream, ...)</tt>
    saves typing work, but since avr-gcc needs to resort to pass all
    arguments of variadic functions on the stack (as opposed to passing
    them in registers for functions that take a fixed number of
    parameters), the ability to pass one parameter less by implying
    \c stdin will also save some execution time.
*/

#if !defined(__DOXYGEN__)

/*
 * This is an internal structure of the library that is subject to be
 * changed without warnings at any time.  Please do *never* reference
 * elements of it beyond by using the official interfaces provided.
 */
struct __file {
   char   *buf;      /* buffer pointer */
   unsigned char unget;   /* ungetc() buffer */
   uint8_t   flags;      /* flags, see below */
#define __SRD   0x0001      /* OK to read */
#define __SWR   0x0002      /* OK to write */
#define __SSTR   0x0004      /* this is an sprintf/snprintf string */
#define __SPGM   0x0008      /* fmt string is in progmem */
#define __SERR   0x0010      /* found error */
#define __SEOF   0x0020      /* found EOF */
#define __SUNGET 0x040      /* ungetc() happened */
#define __SMALLOC 0x80      /* handle is malloc()ed */
#if 0
/* possible future extensions, will require uint16_t flags */
#define __SRW   0x0100      /* open for reading & writing */
#define __SLBF   0x0200      /* line buffered */
#define __SNBF   0x0400      /* unbuffered */
#define __SMBF   0x0800      /* buf is from malloc */
#endif
   int   size;      /* size of buffer */
   int   len;      /* characters read or written so far */
   int   (*put)(char, struct __file *);   /* function to write one char to device */
   int   (*get)(struct __file *);   /* function to read one char from device */
   void   *udata;      /* User defined and accessible data. */
};

#endif /* not __DOXYGEN__ */

/*@{*/
/**
   \c FILE is the opaque structure that is passed around between the
   various standard IO functions.
*/
#define FILE   struct __file

/**
   Stream that will be used as an input stream by the simplified
   functions that don't take a \c stream argument.

   The first stream opened with read intent using \c fdevopen()
   will be assigned to \c stdin.
*/
#define stdin (__iob[0])

/**
   Stream that will be used as an output stream by the simplified
   functions that don't take a \c stream argument.

   The first stream opened with write intent using \c fdevopen()
   will be assigned to both, \c stdin, and \c stderr.
*/
#define stdout (__iob[1])

/**
   Stream destined for error output.  Unless specifically assigned,
   identical to \c stdout.

   If \c stderr should point to another stream, the result of
   another \c fdevopen() must be explicitly assigned to it without
   closing the previous \c stderr (since this would also close
   \c stdout).
*/
#define stderr (__iob[2])

/**
   \c EOF declares the value that is returned by various standard IO
   functions in case of an error.  Since the AVR platform (currently)
   doesn't contain an abstraction for actual files, its origin as
   "end of file" is somewhat meaningless here.
*/
#define EOF   (-1)

/** This macro inserts a pointer to user defined data into a FILE
    stream object.

    The user data can be useful for tracking state in the put and get
    functions supplied to the fdevopen() function. */
#define fdev_set_udata(stream, u) do { (stream)->udata = u; } while(0)

/** This macro retrieves a pointer to user defined data from a FILE
    stream object. */
#define fdev_get_udata(stream) ((stream)->udata)

#if defined(__DOXYGEN__)
/**
   \brief Setup a user-supplied buffer as an stdio stream

   This macro takes a user-supplied buffer \c stream, and sets it up
   as a stream that is valid for stdio operations, similar to one that
   has been obtained dynamically from fdevopen(). The buffer to setup
   must be of type FILE.

   The arguments \c put and \c get are identical to those that need to
   be passed to fdevopen().

   The \c rwflag argument can take one of the values _FDEV_SETUP_READ,
   _FDEV_SETUP_WRITE, or _FDEV_SETUP_RW, for read, write, or read/write
   intent, respectively.

   \note No assignments to the standard streams will be performed by
   fdev_setup_stream().  If standard streams are to be used, these
   need to be assigned by the user.  See also under
   \ref stdio_without_malloc "Running stdio without malloc()".
 */
#define fdev_setup_stream(stream, put, get, rwflag)
#else  /* !DOXYGEN */
#define fdev_setup_stream(stream, p, g, f) \
   do { \
      (stream)->put = p; \
      (stream)->get = g; \
      (stream)->flags = f; \
      (stream)->udata = 0; \
   } while(0)
#endif /* DOXYGEN */

#define _FDEV_SETUP_READ  __SRD   /**< fdev_setup_stream() with read intent */
#define _FDEV_SETUP_WRITE __SWR   /**< fdev_setup_stream() with write intent */
#define _FDEV_SETUP_RW    (__SRD|__SWR)   /**< fdev_setup_stream() with read/write intent */

/**
 * Return code for an error condition during device read.
 *
 * To be used in the get function of fdevopen().
 */
#define _FDEV_ERR (-1)

/**
 * Return code for an end-of-file condition during device read.
 *
 * To be used in the get function of fdevopen().
 */
#define _FDEV_EOF (-2)

#if defined(__DOXYGEN__)
/**
   \brief Initializer for a user-supplied stdio stream

   This macro acts similar to fdev_setup_stream(), but it is to be
   used as the initializer of a variable of type FILE.

   The remaining arguments are to be used as explained in
   fdev_setup_stream().
 */
#define FDEV_SETUP_STREAM(put, get, rwflag)
#else  /* !DOXYGEN */
#define FDEV_SETUP_STREAM(p, g, f) \
   { \
      .put = p, \
      .get = g, \
      .flags = f, \
      .udata = 0, \
   }
#endif /* DOXYGEN */

#ifdef __cplusplus
extern "C" {
#endif

#if !defined(__DOXYGEN__)
/*
 * Doxygen documentation can be found in fdevopen.c.
 */

extern struct __file *__iob[];

#if defined(__STDIO_FDEVOPEN_COMPAT_12)
/*
 * Declare prototype for the discontinued version of fdevopen() that
 * has been in use up to avr-libc 1.2.x.  The new implementation has
 * some backwards compatibility with the old version.
 */
extern FILE *fdevopen(int (*__put)(char), int (*__get)(void),
                      int __opts __attribute__((unused)));
#else  /* !defined(__STDIO_FDEVOPEN_COMPAT_12) */
/* New prototype for avr-libc 1.4 and above. */
extern FILE *fdevopen(int (*__put)(char, FILE*), int (*__get)(FILE*));
#endif /* defined(__STDIO_FDEVOPEN_COMPAT_12) */

#endif /* not __DOXYGEN__ */

/**
   This function closes \c stream, and disallows and further
   IO to and from it.

   When using fdevopen() to setup the stream, a call to fclose() is
   needed in order to free the internal resources allocated.

   If the stream has been set up using fdev_setup_stream() or
   FDEV_SETUP_STREAM(), use fdev_close() instead.

   It currently always returns 0 (for success).
*/
extern int   fclose(FILE *__stream);

/**
   This macro frees up any library resources that might be associated
   with \c stream.  It should be called if \c stream is no longer
   needed, right before the application is going to destroy the
   \c stream object itself.

   (Currently, this macro evaluates to nothing, but this might change
   in future versions of the library.)
*/
#if defined(__DOXYGEN__)
# define fdev_close()
#else
# define fdev_close() ((void)0)
#endif

/**
   \c vfprintf is the central facility of the \c printf family of
   functions.  It outputs values to \c stream under control of a
   format string passed in \c fmt.  The actual values to print are
   passed as a variable argument list \c ap.

   \c vfprintf returns the number of characters written to \c stream,
   or \c EOF in case of an error.  Currently, this will only happen
   if \c stream has not been opened with write intent.

   The format string is composed of zero or more directives: ordinary
   characters (not \c %), which are copied unchanged to the output
   stream; and conversion specifications, each of which results in
   fetching zero or more subsequent arguments.  Each conversion
   specification is introduced by the \c % character.  The arguments must
   properly correspond (after type promotion) with the conversion
   specifier.  After the \c %, the following appear in sequence:

   - Zero or more of the following flags:
      <ul>
      <li> \c # The value should be converted to an "alternate form".  For
            c, d, i, s, and u conversions, this option has no effect.
            For o conversions, the precision of the number is
            increased to force the first character of the output
            string to a zero (except if a zero value is printed with
            an explicit precision of zero).  For x and X conversions,
            a non-zero result has the string `0x' (or `0X' for X
            conversions) prepended to it.</li>
      <li> \c 0 (zero) Zero padding.  For all conversions, the converted
            value is padded on the left with zeros rather than blanks.
            If a precision is given with a numeric conversion (d, i,
            o, u, i, x, and X), the 0 flag is ignored.</li>
      <li> \c - A negative field width flag; the converted value is to be
            left adjusted on the field boundary.  The converted value
            is padded on the right with blanks, rather than on the
            left with blanks or zeros.  A - overrides a 0 if both are
            given.</li>
      <li> ' ' (space) A blank should be left before a positive number
            produced by a signed conversion (d, or i).</li>
      <li> \c + A sign must always be placed before a number produced by a
            signed conversion.  A + overrides a space if both are
            used.</li>
      </ul>

   -   An optional decimal digit string specifying a minimum field width.
       If the converted value has fewer characters than the field width, it
       will be padded with spaces on the left (or right, if the left-adjustment
       flag has been given) to fill out the field width.
   -   An optional precision, in the form of a period . followed by an
       optional digit string.  If the digit string is omitted, the
       precision is taken as zero.  This gives the minimum number of
       digits to appear for d, i, o, u, x, and X conversions, or the
       maximum number of characters to be printed from a string for \c s
       conversions.
   -   An optional \c l or \c h length modifier, that specifies that the
       argument for the d, i, o, u, x, or X conversion is a \c "long int"
       rather than \c int. The \c h is ignored, as \c "short int" is
       equivalent to \c int.
   -   A character that specifies the type of conversion to be applied.

   The conversion specifiers and their meanings are:

   - \c diouxX The int (or appropriate variant) argument is converted
           to signed decimal (d and i), unsigned octal (o), unsigned
           decimal (u), or unsigned hexadecimal (x and X) notation.
           The letters "abcdef" are used for x conversions; the
           letters "ABCDEF" are used for X conversions.  The
           precision, if any, gives the minimum number of digits that
           must appear; if the converted value requires fewer digits,
           it is padded on the left with zeros.
   - \c p  The <tt>void *</tt> argument is taken as an unsigned integer,
           and converted similarly as a <tt>%\#x</tt> command would do.
   - \c c  The \c int argument is converted to an \c "unsigned char", and the
           resulting character is written.
   - \c s  The \c "char *" argument is expected to be a pointer to an array
           of character type (pointer to a string).  Characters from
           the array are written up to (but not including) a
           terminating NUL character; if a precision is specified, no
           more than the number specified are written.  If a precision
           is given, no null character need be present; if the
           precision is not specified, or is greater than the size of
           the array, the array must contain a terminating NUL
           character.
   - \c %  A \c % is written.  No argument is converted.  The complete
           conversion specification is "%%".
   - \c eE The double argument is rounded and converted in the format
           \c "[-]d.ddde±dd" where there is one digit before the
           decimal-point character and the number of digits after it
           is equal to the precision; if the precision is missing, it
           is taken as 6; if the precision is zero, no decimal-point
           character appears.  An \e E conversion uses the letter \c 'E'
           (rather than \c 'e') to introduce the exponent.  The exponent
           always contains two digits; if the value is zero,
           the exponent is 00.
   - \c fF The double argument is rounded and converted to decimal notation
           in the format \c "[-]ddd.ddd", where the number of digits after the
           decimal-point character is equal to the precision specification.
           If the precision is missing, it is taken as 6; if the precision
           is explicitly zero, no decimal-point character appears.  If a
           decimal point appears, at least one digit appears before it.
   - \c gG The double argument is converted in style \c f or \c e (or
           \c F or \c E for \c G conversions).  The precision
           specifies the number of significant digits.  If the
           precision is missing, 6 digits are given; if the precision
           is zero, it is treated as 1.  Style \c e is used if the
           exponent from its conversion is less than -4 or greater
           than or equal to the precision.  Trailing zeros are removed
           from the fractional part of the result; a decimal point
           appears only if it is followed by at least one digit.
   - \c S  Similar to the \c s format, except the pointer is expected to
           point to a program-memory (ROM) string instead of a RAM string.

   In no case does a non-existent or small field width cause truncation of a
   numeric field; if the result of a conversion is wider than the field
   width, the field is expanded to contain the conversion result.

   Since the full implementation of all the mentioned features becomes
   fairly large, three different flavours of vfprintf() can be
   selected using linker options.  The default vfprintf() implements
   all the mentioned functionality except floating point conversions.
   A minimized version of vfprintf() is available that only implements
   the very basic integer and string conversion facilities, but only
   the \c # additional option can be specified using conversion
   flags (these flags are parsed correctly from the format
   specification, but then simply ignored).  This version can be
   requested using the following \ref gcc_minusW "compiler options":

   \code
   -Wl,-u,vfprintf -lprintf_min
   \endcode

   If the full functionality including the floating point conversions
   is required, the following options should be used:

   \code
   -Wl,-u,vfprintf -lprintf_flt -lm
   \endcode

   \par Limitations:
   - The specified width and precision can be at most 255.

   \par Notes:
   - For floating-point conversions, if you link default or minimized
     version of vfprintf(), the symbol \c ? will be output and double
     argument will be skiped. So you output below will not be crashed.
     For default version the width field and the "pad to left" ( symbol
     minus ) option will work in this case.
   - The \c hh length modifier is ignored (\c char argument is
     promouted to \c int). More exactly, this realization does not check
     the number of \c h symbols.
   - But the \c ll length modifier will to abort the output, as this
     realization does not operate \c long \c long arguments.
   - The variable width or precision field (an asterisk \c * symbol)
     is not realized and will to abort the output.

 */

extern int   vfprintf(FILE *__stream, const char *__fmt, va_list __ap);

/**
   Variant of \c vfprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   vfprintf_P(FILE *__stream, const char *__fmt, va_list __ap);

/**
   The function \c fputc sends the character \c c (though given as type
   \c int) to \c stream.  It returns the character, or \c EOF in case
   an error occurred.
*/
extern int   fputc(int __c, FILE *__stream);

#if !defined(__DOXYGEN__)

/* putc() function implementation, required by standard */
extern int   putc(int __c, FILE *__stream);

/* putchar() function implementation, required by standard */
extern int   putchar(int __c);

#endif /* not __DOXYGEN__ */

/**
   The macro \c putc used to be a "fast" macro implementation with a
   functionality identical to fputc().  For space constraints, in
   \c avr-libc, it is just an alias for \c fputc.
*/
#define putc(__c, __stream) fputc(__c, __stream)

/**
   The macro \c putchar sends character \c c to \c stdout.
*/
#define putchar(__c) fputc(__c, stdout)

/**
   The function \c printf performs formatted output to stream
   \c stderr.  See \c vfprintf() for details.
*/
extern int   printf(const char *__fmt, ...);

/**
   Variant of \c printf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   printf_P(const char *__fmt, ...);

/**
   The function \c vprintf performs formatted output to stream
   \c stdout, taking a variable argument list as in vfprintf().

   See vfprintf() for details.
*/
extern int   vprintf(const char *__fmt, va_list __ap);

/**
   Variant of \c printf() that sends the formatted characters
   to string \c s.
*/
extern int   sprintf(char *__s, const char *__fmt, ...);

/**
   Variant of \c sprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   sprintf_P(char *__s, const char *__fmt, ...);

/**
   Like \c sprintf(), but instead of assuming \c s to be of infinite
   size, no more than \c n characters (including the trailing NUL
   character) will be converted to \c s.

   Returns the number of characters that would have been written to
   \c s if there were enough space.
*/
extern int   snprintf(char *__s, size_t __n, const char *__fmt, ...);

/**
   Variant of \c snprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   snprintf_P(char *__s, size_t __n, const char *__fmt, ...);

/**
   Like \c sprintf() but takes a variable argument list for the
   arguments.
*/
extern int   vsprintf(char *__s, const char *__fmt, va_list ap);

/**
   Variant of \c vsprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   vsprintf_P(char *__s, const char *__fmt, va_list ap);

/**
   Like \c vsprintf(), but instead of assuming \c s to be of infinite
   size, no more than \c n characters (including the trailing NUL
   character) will be converted to \c s.

   Returns the number of characters that would have been written to
   \c s if there were enough space.
*/
extern int   vsnprintf(char *__s, size_t __n, const char *__fmt, va_list ap);

/**
   Variant of \c vsnprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   vsnprintf_P(char *__s, size_t __n, const char *__fmt, va_list ap);
/**
   The function \c fprintf performs formatted output to \c stream.
   See \c vfprintf() for details.
*/
extern int   fprintf(FILE *__stream, const char *__fmt, ...);

/**
   Variant of \c fprintf() that uses a \c fmt string that resides
   in program memory.
*/
extern int   fprintf_P(FILE *__stream, const char *__fmt, ...);

/**
   Write the string pointed to by \c str to stream \c stream.

   Returns 0 on success and EOF on error.
*/
extern int   fputs(const char *__str, FILE *__stream);

/**
   Variant of fputs() where \c str resides in program memory.
*/
extern int   fputs_P(const char *__str, FILE *__stream);

/**
   Write the string pointed to by \c str, and a trailing newline
   character, to \c stdout.
*/
extern int   puts(const char *__str);

/**
   Variant of puts() where \c str resides in program memory.
*/
extern int   puts_P(const char *__str);

/**
   Write \c nmemb objects, \c size bytes each, to \c stream.
   The first byte of the first object is referenced by \c ptr.

   Returns the number of objects successfully written, i. e.
   \c nmemb unless an output error occured.
 */
extern size_t   fwrite(const void *__ptr, size_t __size, size_t __nmemb,
             FILE *__stream);

/**
   The function \c fgetc reads a character from \c stream.  It returns
   the character, or \c EOF in case end-of-file was encountered or an
   error occurred.  The routines feof() or ferror() must be used to
   distinguish between both situations.
*/
extern int   fgetc(FILE *__stream);

#if !defined(__DOXYGEN__)

/* getc() function implementation, required by standard */
extern int   getc(FILE *__stream);

/* getchar() function implementation, required by standard */
extern int   getchar(void);

#endif /* not __DOXYGEN__ */

/**
   The macro \c getc used to be a "fast" macro implementation with a
   functionality identical to fgetc().  For space constraints, in
   \c avr-libc, it is just an alias for \c fgetc.
*/
#define getc(__stream) fgetc(__stream)

/**
   The macro \c getchar reads a character from \c stdin.  Return
   values and error handling is identical to fgetc().
*/
#define getchar() fgetc(stdin)

/**
   The ungetc() function pushes the character \c c (converted to an
   unsigned char) back onto the input stream pointed to by \c stream.
   The pushed-back character will be returned by a subsequent read on
   the stream.

   Currently, only a single character can be pushed back onto the
   stream.

   The ungetc() function returns the character pushed back after the
   conversion, or \c EOF if the operation fails.  If the value of the
   argument \c c character equals \c EOF, the operation will fail and
   the stream will remain unchanged.
*/
extern int   ungetc(int __c, FILE *__stream);

/**
   Read at most <tt>size - 1</tt> bytes from \c stream, until a
   newline character was encountered, and store the characters in the
   buffer pointed to by \c str.  Unless an error was encountered while
   reading, the string will then be terminated with a \c NUL
   character.

   If an error was encountered, the function returns NULL and sets the
   error flag of \c stream, which can be tested using ferror().
   Otherwise, a pointer to the string will be returned.  */
extern char   *fgets(char *__str, int __size, FILE *__stream);

/**
   Similar to fgets() except that it will operate on stream \c stdin,
   and the trailing newline (if any) will not be stored in the string.
   It is the caller's responsibility to provide enough storage to hold
   the characters read.  */
extern char   *gets(char *__str);

/**
   Read \c nmemb objects, \c size bytes each, from \c stream,
   to the buffer pointed to by \c ptr.

   Returns the number of objects successfully read, i. e.
   \c nmemb unless an input error occured or end-of-file was
   encountered.  feof() and ferror() must be used to distinguish
   between these two conditions.
 */
extern size_t   fread(void *__ptr, size_t __size, size_t __nmemb,
            FILE *__stream);

/**
   Clear the error and end-of-file flags of \c stream.
 */
extern void   clearerr(FILE *__stream);

#if !defined(__DOXYGEN__)
/* fast inlined version of clearerr() */
#define clearerror(s) do { (s)->flags &= ~(__SERR | __SEOF); } while(0)
#endif /* !defined(__DOXYGEN__) */

/**
   Test the end-of-file flag of \c stream.  This flag can only be cleared
   by a call to clearerr().
 */
extern int   feof(FILE *__stream);

#if !defined(__DOXYGEN__)
/* fast inlined version of feof() */
#define feof(s) ((s)->flags & __SEOF)
#endif /* !defined(__DOXYGEN__) */

/**
   Test the error flag of \c stream.  This flag can only be cleared
   by a call to clearerr().
 */
extern int   ferror(FILE *__stream);

#if !defined(__DOXYGEN__)
/* fast inlined version of ferror() */
#define ferror(s) ((s)->flags & __SERR)
#endif /* !defined(__DOXYGEN__) */

extern int   vfscanf(FILE *__stream, const char *__fmt, va_list __ap);

/**
   Variant of vfscanf() using a \c fmt string in program memory.
 */
extern int   vfscanf_P(FILE *__stream, const char *__fmt, va_list __ap);

/**
   The function \c fscanf performs formatted input, reading the
   input data from \c stream.

   See vfscanf() for details.
 */
extern int   fscanf(FILE *__stream, const char *__fmt, ...);

/**
   Variant of fscanf() using a \c fmt string in program memory.
 */
extern int   fscanf_P(FILE *__stream, const char *__fmt, ...);

/**
   The function \c scanf performs formatted input from stream \c stdin.

   See vfscanf() for details.
 */
extern int   scanf(const char *__fmt, ...);

/**
   Variant of scanf() where \c fmt resides in program memory.
 */
extern int   scanf_P(const char *__fmt, ...);

/**
   The function \c vscanf performs formatted input from stream
   \c stdin, taking a variable argument list as in vfscanf().

   See vfscanf() for details.
*/
extern int   vscanf(const char *__fmt, va_list __ap);

/**
   The function \c sscanf performs formatted input, reading the
   input data from the buffer pointed to by \c buf.

   See vfscanf() for details.
 */
extern int   sscanf(const char *__buf, const char *__fmt, ...);

/**
   Variant of sscanf() using a \c fmt string in program memory.
 */
extern int   sscanf_P(const char *__buf, const char *__fmt, ...);

#if defined(__DOXYGEN__)
/**
   Flush \c stream.

   This is a null operation provided for source-code compatibility
   only, as the standard IO implementation currently does not perform
   any buffering.
 */
extern int   fflush(FILE *stream);
#else
static __inline__ int fflush(FILE *stream __attribute__((unused)))
{
   return 0;
}
#endif

#ifdef __cplusplus
}
#endif

/*@}*/

/*
 * The following constants are currently not used by avr-libc's
 * stdio subsystem.  They are defined here since the gcc build
 * environment expects them to be here.
 */
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2

#endif /* __ASSEMBLER */

#endif /* _STDLIB_H_ */

ptr128 писал(а):
видим только одну локальную скрытую функцию
на самом деле больше одной - см. выше. так что моя гипотеза вполне себе верна: во-первых, я сделал допущение, во-вторых в виде примера привел не всю avr-libc, а только один из ее модулей, т.к. что если этот пример вами опровергнут - опровергайте основное предположение о том, что многие внутренние ф-ии скрыты, на основе всех исходников всей avr-libc...

а вот чего вы хотите? может, вам тут среди неучей-любителей скучно сверкать бриллиантами 30-летнего ПРОФЕССИОНАЛЬНОГО программирования? ну так сверкайте на профессиональных форумах. или вы хотите заменить собой всех, кто готов помогать другим только на основе своего, любительского, опыта? ну так это тоже можно: поиск на форуме выдаст вам кучу тем, где новички задают вопросы по программированию - сверкайте тогда уж и там!

_________________
если рассматривать человека снизу, покажется, что мозг у него глубоко в жопе
при взгляде на многих сверху ничего не меняется...

Мой уютный бложик... заходите!


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 12:52:25 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 0
Это связано с тем, что для лучшей читабельности кода, рекомендуется функции делать не длинее, чем на 2-3 экрана (порядка сотни строк). Само собой, увеличение количества функций приводит к большей их вложенности. Зато понять, что делает каждая функция намного проще и редактировать код удобней. Ведь вместо того, чтобы лазить стрелками или листанием страниц по длинющему коду можно сразу прыгать на нужную функцию.

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 13:13:30 
Вымогатель припоя
Аватар пользователя

Зарегистрирован: Пт янв 18, 2013 15:11:02
Сообщений: 516
Рейтинг сообщения: 0
Подскажите почему в Disassemblere видит как не найденный файла.
СпойлерИзображение


Функция на СИ:
Код:
if((chetTimer1==Tst2)&&(lampcontr==0))
      {
         
      PORTB&=~(1<<PORTB2);
            asm("nop");
         chetTimer1=0;                  }
                                    


Вложения:
обрыв файла.png [136.26 KiB]
Скачиваний: 452
Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 13:54:30 
Встал на лапы
Аватар пользователя

Зарегистрирован: Чт апр 26, 2012 14:30:40
Сообщений: 93
Откуда: под Москвой
Рейтинг сообщения: 0
ARV писал(а):
а вот чего вы хотите? может, вам тут с.....


ARV, я конечно кот здесь мелкий, но все таки не нужно ссориться, мало-ли кто как выразился неудачно, ptr128 в общем то выразил просто свое удивление, т.к. высокого о Вас мнения...
С Уважением.


а ошибаться можем мы все, даже в том что постоянно делаем, я вот сейчас в маркировке плат напортачил отправляя в Резонит, пришлось пересылать проект....


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 14:27:55 
Ум, честь и совесть. И скромность.
Аватар пользователя

Карма: 98
Рейтинг сообщений: 2135
Зарегистрирован: Чт дек 28, 2006 08:19:56
Сообщений: 18436
Откуда: Новочеркасск
Рейтинг сообщения: 0
Медали: 2
Получил миской по аватаре (1) Мявтор 3-й степени (1)
ошибаться могут все. кроме некоторых - наверное, вы заметили, что на форуме есть некоторые, кто никогда ни в чем не ошибается? один из них - КРАМ: что ни слово, то хоть в граните отливай. точка. особенно мне не по душе, когда вопрос идет на принципе: вот я прав и докажу это!

кого из "тусующихся" здесь интересуют исходники libc ? да, они доступны. да, есть люди, которые их изучают, улучшают и т.п. но кто из присутствующих здесь этим занимается? все пользуются ими - а это подразумевает только тот интерфейс, который описан в документации libc. ну нет в документации функций _IO_vfprintf и других - так для чего их тут приводить?

тем более что на самом деле, с точки зрения формальной логики, нет никакого противоречия в сказанном мною и ptr128. но из принципа надо доказать, что есть еще среди нас неучи, которые даже ни разу в исходники libc не заглядывали, а умничают...

strengerst писал(а):
Подскажите почему в Disassemblere видит как не найденный файла.
очень просто: вы видите так называемый strtup-код, который компилятор вставляет сам, без ваших усилий: первичная инициализация static-переменных, установка указателя стека и т.п. подготовительные операции, которые обязательно должны быть. и естественно, что этот код не может быть найден ни в одном из ваших исходников - вот дизассемблер вам и сообщает об этом.

_________________
если рассматривать человека снизу, покажется, что мозг у него глубоко в жопе
при взгляде на многих сверху ничего не меняется...

Мой уютный бложик... заходите!


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 14:33:37 
Вымогатель припоя
Аватар пользователя

Зарегистрирован: Пт янв 18, 2013 15:11:02
Сообщений: 516
Рейтинг сообщения: 0
Большое спасибо.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 15:01:32 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 0
ARV писал(а):
ошибаться могут все. кроме некоторых - наверное, вы заметили, что на форуме есть некоторые, кто никогда ни в чем не ошибается?

При чем тут это? Вы уж точно знаете, что я публично признаю свои ошибки на форуме, если я не прав. И это случалось уже не раз.

ARV писал(а):
кого из "тусующихся" здесь интересуют исходники libc ?

Вас. Вы же начали рассуждать про libc:
ARV писал(а):
допустим, sprintf - открытая библиотечная функция

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 15:07:39 
Ум, честь и совесть. И скромность.
Аватар пользователя

Карма: 98
Рейтинг сообщений: 2135
Зарегистрирован: Чт дек 28, 2006 08:19:56
Сообщений: 18436
Откуда: Новочеркасск
Рейтинг сообщения: 0
Медали: 2
Получил миской по аватаре (1) Мявтор 3-й степени (1)
ptr128 писал(а):
Вас. Вы же начали рассуждать про libc:
ARV писал(а):
допустим, sprintf - открытая библиотечная функция
правильно, я взял библиотечную функцию, интерфейс к которой открыт в stdio.h. разве нет? есть ли в этом интерфейсе библиотеки пользователя упоминаемые вами функции? код заголовочника я процитировал. их нет. разве я говорил, что-то о ПРОЕКТЕ libc? нет, не говорил. я говорил об интерфейсе к билиотеке. что не так?

P.S. уж совсем в порядке оффтопа... спрошу лично вашего мнения, ptr128: вы тоже считаете, что не существует отличия между ФУНКЦИЕЙ и ПРОЦЕДУРОЙ в программировании? эти два понятия разделяются по смыслу и работе или они эквивалентны?

_________________
если рассматривать человека снизу, покажется, что мозг у него глубоко в жопе
при взгляде на многих сверху ничего не меняется...

Мой уютный бложик... заходите!


Вернуться наверх
 
Не в сети
 Заголовок сообщения: Re: Нескольно простых вопросов о программировании AVR на Си.
СообщениеДобавлено: Пт ноя 25, 2016 15:43:26 
Вымогатель припоя
Аватар пользователя

Карма: 19
Рейтинг сообщений: 230
Зарегистрирован: Чт окт 06, 2016 21:12:07
Сообщений: 606
Откуда: Южное Бутово
Рейтинг сообщения: 0
ARV писал(а):
вы тоже считаете, что не существует отличия между ФУНКЦИЕЙ и ПРОЦЕДУРОЙ в программировании? эти два понятия разделяются по смыслу и работе или они эквивалентны?

Если речь только в рамках топика, то для C со времен K&R отличий в смысле и работе не предусматривается.
При этом существует ряд языков, в которых функции и процедуры явно разделены.
Более того, например в SQL проводится резкое различие между скалярными, агрегативными и recordset функциями.

Возвращаясь к C, IMHO, считаю разделение функций возвращающих значение и не возвращающих субуго субъективным. Например, в MISRA void функции вообще запрещены, так как там функция обязана всегда возвращать код завершения. Лично я допускаю использование void функций в тех случаях, когда код из завершения всегда будет нулевым.

_________________
Не ошибается только то, кто ничего не делает.
Тот, кто признает свои ошибки, на них учится.
Глупец же, упорствуя в своих заблуждениях, остается глупцом.


Вернуться наверх
 
Показать сообщения за:  Сортировать по:  Вернуться наверх
Начать новую тему Ответить на тему  [ Сообщений: 1499 ]     ... , , , 22, , , ...  

Часовой пояс: UTC + 3 часа


Кто сейчас на форуме

Сейчас этот форум просматривают: alsav22 и гости: 19


Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Найти:
Перейти:  


Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
Русская поддержка phpBB
Extended by Karma MOD © 2007—2012 m157y
Extended by Topic Tags MOD © 2012 m157y