Pull to refresh

Comments 30

Простите, а как C повлиял на F#?
И правда, F# здесь лишний. Исправил)
>Стандарт С99 сейчас в большей или меньшей степени поддерживается всеми современными компиляторами языка Си.

Всеми, кроме Микрософтовской студии! Там по сути нет компилятора именно языка Си! Часто эти грабли доставляли при попытках собрать библиотеки.
А я в студии собирал такой код:
main() { printf("Hello world!\n"); }

Хотя C++ компилятор бы его обматерил)
Почему? Не обматерил бы. Инклюд stdio.h и вуаля.
отсутствие инклуда как раз является фишкой :)
а… ) Студия небось его автоматом подключает… я ее всего пару раз в глаза видел, поэтому хз)
эм… ни один сишный компилятор не инклудит автоматом заголовки, он просто предугадывает сигнатуру у методов по ее входным аргументам и считает, что она возвращает int
Я слышал, что студия как ide много чего сама делает, поэтому и предположил. Тот же g++ выдает ошибку при попытке собрать этот код без инклюда, он, похоже, ничего не предугадывает.
~/labs $ cat main.c 
main() { printf("Hello world!\n"); }

~/labs $ gcc main.c -o main
main.c: In function ‘main’:
main.c:1:10: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
~/labs $ ./main 
Hello world!


g++ предназначен для сборки C++ кода, а вот gcc прекрасно справляется
ну дык я о с++ и говорил… понятное дело, что сишный справится с этим кодом)
По стандарту современного Си, если функция возвращает int (как это делает printf, например), объявление её прототипа не требуется, то есть файлы типа stdio.h подключать не нужно.
Можете объяснить, пожалуйста. Просто не понимаю: если не подключать заголовочный файл, откуда компилятор знает, что возвращает функция printf… и откуда её вызывать
если сишный компилятор не находит объявление функции «foo», то он считает, что она задана следующим образом:
int foo(...);
если бы компилятор считал, что это функция не принимает аргументы, то тот же printf бы не отработал. фишка именно в том, что по дефолту в си функция — это функция с переменным количеством аргументов
В Си int foo(void) это функция без аргументов. А int foo() — с аргументами.
«откуда компилятор знает … откуда её [printf] вызывать»

Компилятор этими вопросами не занимается, он просто вставляет ссылку на символ _printf в генерируемом объектном файле и все. Это задача линковщика — найти определение всех символов и скомпоновать из набора объектных файлов и библиотек исполняемый файл. Линковщик находит определение символа _printf, потому что по-умолчанию стандартная библиотека языка Си (libc) всегда участвует в линковке.
Спасибо, последний факт как раз не знал, и не доставало, что бы понять
С99 там в студии нет и не будет.
Там по сути нет компилятора именно языка Си!

Отдельного компилятора нет, но cl.exe успешно умеет им притворяться:
image
«Отдельного компилятора нет, но cl.exe успешно умеет им притворяться»

Но C99 он не переваривает.

struct foo { int bar; } foo = { .bar = 42 };
int data[] = {[3] = 0, [2] = 1, [1] = 2, [0] = 3};
Попробуйте положить код в файл с расширением .c вместо .cpp и все получится.
Эх, си++ за 21 день, сколько лет то уже прошло, а так дальше char * str = «7 stroka, proverit»; и не пролез =)
такой код не соберется %)

а вообще, чтобы изучить язык — на нем надо писать, много писать. практически в любом предмете теория бесполезна без практики
Да по хорошему, теория начинает хорошо усваиваться только, если есть некоторый практический опыт. Поэтому проще поучавствовать в опенсорс проекте каком-нибудь, желательно качественном и с толковым лидером, ну а там поднатаскают уже в плане практики и книжки с теорией станут куда легче читаться и они наконец начнут пониматься и запоминаться!
"… версиях Linux содержится более 10 000 000 строк кода), задача о переписывании UNIX на другой язык становиться практически невыполнимой...".
Не сочтите за грубость, но всё же загляните на tsya.ru.

Несколько ссылок и цитат про первые компиляторы C, B, BCPL, AED-0, Bootstrap Compiler; и о том, как компилировался первый компилятор новых языков


Чтобы написать компилятор Си, авторы создали язык B и компилятор языка B (и его диалекта NB) — http://stackoverflow.com/questions/18125490/how-was-the-first-c-compiler-written "How was the first C compiler written?"
https://www.bell-labs.com/usr/dmr/www/chist.html "The Development of the C Language* Dennis M. Ritchie"
Для написания компилятора языка B использовался язык BCPL (хотя позже компилятор B был переписан на B). Компилятор BCPL был уже портирован для Multics и GE 635 GECOS в Bell Labs (цит. по The Development of the C):


История компилятора BCPL и AED-0
BCPL was designed by Martin Richards in the mid-1960s while he was visiting MIT, and was used during the early 1970s for several interesting projects, among them the OS6 operating system at Oxford [Stoy 72], and parts of the seminal Alto work at Xerox PARC [Thacker 79]. We became familiar with it because the MIT CTSS system [Corbato 62] on which Richards worked was used for Multics development. The original BCPL compiler was transported both to Multics and to the GE-635 GECOS system by Rudd Canaday and others at Bell Labs [Canaday 69]; during the final throes of Multics's life at Bell Labs and immediately after, it was the language of choice among the group of people who would later become involved with Unix.

Компилятор BCPL (Basic Combined Programming Language) был создан Martin Richards (http://www.cl.cam.ac.uk/~mr10/) в MIT к 1967 году:
https://www.bell-labs.com/usr/dmr/www/bcpl.html "Martin Richards's BCPL Reference Manual, 1967"
http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf "Massachusetts Institute of Technology. Project MAC. Memorandum-M-352, July 21, 1967. The BCPL Reference Manual" (скан от Karl Kleine — http://www.eah-jena.de/~kleine/history/)
https://www.bell-labs.com/usr/dmr/www/bcpl.pdf "The BCPL Reference Manual", 1967 (OCR by Dennis M. Ritchie)
https://www.computer.org/csdl/proceedings/afips/1969/5073/00/50730557.pdf "BCPL: A tool for compiler writing and system programming", Martin Richards, Proceedings of the May 14-16, 1969, spring joint computer conference (pp. 557-566)


Он имел разделение на две части: компилятор из языка в промежуточный код O-code и транслятор O-кода в машинный код, см стр 12 Iain D. Craig. Virtual Machines — Springer 2010 isbn 1846282462 (глава 2):


BCPL was intended to be portable. Portability is achieved by bootstrapping the runtime system a number of times so that it eventually implements the compliler's output language. This language is called OCODE. OCODE is similar to a high-level assembly language… also defined in such a way that it could be translated into the machine language of most processors.…
In the book on BCPL [45], Richards and Whitby-Strevens define a second low-level intermediate language called Intcode. Intcode is an extremely simple language that can be used to bootstrap OCODE.… The BCPL system was distributed in OCODE form.

Таким образом, для запуска компилятора BCPL, который распространялся в кодах OCODE и компилировал программы с BCPL в OCODE, требовался транслятор OCODE. Транслятор OCODE написан на Intcode, а Intcode уже достаточно прост для реализации без языков высокого уровня (единицы дней для ассемблера и интерпретатора Intcode на новой машине; хотя реализация Intcode на самом BCPL тоже возможна). Осталось лишь скомпилировать первый компилятор BCPL, написанный на BCPL в OCODE https://www.bell-labs.com/usr/dmr/www/bcpl.html:


Richards's first BCPL compiler was written using the 6-bit BCD character set on CTSS, and adapted shortly thereafter to use the characters available on the IBM "golf-ball" 1050 and 2741 terminals.

У Martin Richards — http://www.cl.cam.ac.uk/~mr10/ опубликованы разные компиляторы BCPL, как современный http://www.cl.cam.ac.uk/~mr10/BCPL.html, так и BCPLCTSS от 1968 года:
http://www.cl.cam.ac.uk/~mr10/BCPLCTSS.htmlhttp://www.cl.cam.ac.uk/users/mr/BCPLCTSS/bcplctss.zip


BCPLCTSS contains the version of the BCPL compiler as it was in June 1968 running on CTSS at MIT's Project MAC. It also contains a modification of this compiler that runs under the current 64-bit Cintcode BCPL System. Click BCPLCTSS.html to obtain a copy.
I have typed in the source code from IBM golf ball listing of the compiler dating back to between February and June 1968.

На странице http://www.math.bas.bg/bantchev/place/bcpl.html есть фрагмент цитаты Martin Richards о ранних компиляторах BCPL "‘[…] reimplemented in BCPL, the first compiler was a mere 1000 lines long’" — т.е. компилятор BCPL на BCPL размером в 1 тыс. строк был не первым компилятором BCPL! Позже он вырос до 88 стр. — по "BCPL: A tool.." — "BCPL compiler itself consists of 88 pages of BCPL program and contains only 29 labels"


В http://www.cl.cam.ac.uk/~mr10/bcplman.pdf "The BCPL Cintsys and Cintpos User Guide", 2016 Martin Richards указал, что на CTSS у него было доступно лишь два языка с рекурсией: Lisp и AED-0 ("AED-0 language based on ALGOL-60") от Douglas T. Ross


BCPL was initially similar to this subset of CPL used in the encoding of the CPL compiler. An outline of BCPL’s main features first appeared in my PhD thesis [4] in 1966 but it was not fully designed and implemented until early the following year when I was working at Project MAC of the Massachussetts Institute of Technology. Its first implementation was written in Ross’s Algol Extended for Design (AED-0)[1] which was the only language then available on CTSS, the time sharing system at Project MAC, other than LISP that allowed recursion.

Немного истории AED-0 есть на странице http://groups.csail.mit.edu/mac/projects/studentaut/DR%20HK%20Bio.htm и Compiler Construction. LNCS 21, isbn 3662215497 page 470 (1974) — компилятор AED-0 был переписан на язык AED-0 лишь к концу 1964 года, а в 1963 году заработал изначальный компилятор AED-0 для IBM 7094 (фото), написанный на неуточненном "bootstrap compiler language"


He started programming in July 1952 on the MIT Whirlwind computer and later, through collaboration of his MIT Computer-Aided Design Project with MIT’s Project Mac, on the pioneering Compatible Time-Sharing System (CTSS).… 1962 — 1969: MIT Computer-Aided Design Project (with Project MAC), first software engineering language (AED, Algol Extended for Design)

AED-0 [Ross 69] is a high level language developed by the M.I.T. Computer-Aided Design Project. It is based on ALGOL60 and is aimed at providing a convinient and effective language for creating specialized computer aided design systems for a wide variety of application areas. The original AED-0 compiler written in a bootstrap compiler language became operational on an IBM 709 machine in 1963. Subsequently, it was moved to CTSS of M.I.T. Project MAC operating on an IBM 7094. Further developments were made in this system to produce a fairly stable language by late 1964. By this time, the compiler existed in its own language and all further system changes and improvements were carrier out in AED-0 itself.

Есть ссылка из The BCPL Cintsys… 2016 на работу "D.T. Ross et al. AED-0 programmer’s guide and user kit. Technical report, Electronic Systems Laboratory M.I.T, 1964.", но даже более новые варианты текста недоступны в сети: AED-0 Programmer's Guide. 1970


… Part 1 of the manual describes the AED-0 language proper, including descriptions of several subroutine packages which extend the features of the language beyond the forms derived from Algol-60 syntax.

Идеи, которые привели к созданию AED описываются Ross в Richard L. Wexelblat. History of Programming Languages. Chapter VI APT Session. "Origins of the apt language for automatically programmed tools", 1978


Немного об AED-0 есть в отчете Project MAC "VERBAL AND GRAPHICAL LANGUAGE FOR THE AED SYSTEMI A PROGRESS REPORT" MAC-TR-4
http://publications.csail.mit.edu/lcs/pubs/pdf/MIT-LCS-TR-004.pdf#page=8


THE AED-0 COMPILER
It was found that no existing compiler could provide an efficient mechanization of the plex concept so that in the Spring of 1963 the Project undertook to construct a compiler incorporating the techniques proposed for the Computer-Aided Design System itself as the first major step toward accomplishing the goals of the Project. Prior to that time plex programming had been carried out using an experimental compiler called the Bootstrap Compiler, which also was written by the Project, both for educational experience and as an experimental tool. The AED-0 Compiler was originally written in the Bootstrap Compiler language, but recently the resulting system has been disassembled from binary machine code back into FAP assembly language and a great many changes and improvements to the AED-0 Compiler have been made so that now it is available as a public command in the Project MAC Time-Sharing System. AED-0 language at present consists of Algol-60, with some features omitted, and others for plex programming added. The compiler is very efficient and flexible and compiles very good machine code in most cases. The compiler is based directly on the plex concepts described 1 above.

По языку Bootstrap Compiler информации еще меньше, чем по AED-0. Есть отдельные упоминания в http://www.dtic.mil/dtic/tr/fulltext/u2/681342.pdf Project MAC Progress Report IV (July 1966 to July 1967) и интервью Росса
http://conservancy.umn.edu/bitstream/handle/11299/107611/oh178dtr.pdf?sequence=1 An Interview with DOUGLAS T. ROSS, 1989:


… AED releases, and also from the beginning, AED was a machine independent software engineering job. In fact, we started out in parallel on the 709 and the TX-0, before MAC was even thought of, you see. That was actually the Bootstrap Compiler--in which we first wrote AED [we didn't use FAP]. Then it was that first AED Compiler that we had up and running here within two weeks of Project MAC opening its doors.…
I backed out of the theoretically-beautiful and clean way that we originally were generating AED code and had the whole compiler back-end redone. We did what we called a disassembly. We took the machine code of the compiler, itself, (just a bit- map of memory essentially) and went back as though it had been written in the FAP assembly language, then came back out and reassembled the whole thing so that it would be easier to do patches. Then we changed the whole code-generation part of the compiler to generate the standard (what was called the BBS format of machine-language representation, so that whatever came out of our compiler would fit into the standards that they'd adopted for Project MAC.

Не все компиляторы начинались с компиляторов:
http://en.wikipedia.org/wiki/History_of_compiler_construction#First_compilers
http://en.wikipedia.org/wiki/Bootstrapping_(compilers%29


The first compiler was written by Grace Hopper, in 1952, for the A-0 System language. The term compiler was coined by Hopper.[1][2] The A-0 functioned more as a loader or linker than the modern notion of a compiler. The first autocode and its compiler were developed by Alick Glennie in 1952 for the Mark 1 computer at the University of Manchester and is considered by some to be the first compiled programming language. The FORTRAN team led by John W. Backus at IBM is generally credited as having introduced the first complete compiler, in 1957. The first FORTRAN compiler took 18 person-years to create.[3]
The first ALGOL 58 compiler was completed by the end of 1958 by Friedrich L. Bauer, Hermann Bottenbruch, Heinz Rutishauser, and Klaus Samelson for the Z22 computer. Bauer et al. had been working on compiler technology for the Sequentielle Formelubersetzung (i.e. sequential formula translation) in the previous years.…
The COBOL compiler for the UNIVAC II was probably the first to be written in a high-level language, namely FLOW-MATIC, by a team led by Grace Hopper.

И чуть ниже там же — пример компилятора языка, написанного на этом же языке и запускаемого на интерпретаторе языка:


Building a self-hosting compiler is a bootstrapping problem, i.e. the first such compiler for a language must be either hand written machine code or compiled by a compiler written in another language, or compiled by running the compiler in an interpreter.…
Another early self-hosting compiler was written for Lisp by Tim Hart and Mike Levin at MIT in 1962.[5] They wrote a Lisp compiler in Lisp, testing it inside an existing Lisp interpreter. Once they had improved the compiler to the point where it could compile its own source code, it was self-hosting.[6]…
Forth is an example of a self-hosting compiler. The self compilation and cross compilation features of Forth are commonly confused with metacompilation and metacompilers.
Sign up to leave a comment.

Articles