• How to write programs in C in Ubuntu. Introduction to the C programming language. How to build a program

    Basic Linux programming with GCC

    The Linux operating system has long occupied a leading position in supercomputer software, it ranks second in the Internet server segment and is rapidly gaining popularity in the corporate segment. This is facilitated by the main advantages of Linux compared to commercial operating systems - high economic efficiency, mobility, flexibility, optimal conditions for installing a DBMS.

    On our course "Linux (Ubuntu). Level 2. Programming in Linux in C" You will gain the knowledge and skills necessary to develop software for the rapidly growing popularity of the Linux operating system. You will begin to understand the process of building software and the specifics of the C compiler included in GCC. You will learn to understand the differences between processes and threads, use multithreading and its specifics. You will learn what “daemons” are and how they differ from application software.

    At the Specialist Center, Linux training is carried out using the example of the most popular distribution kit Ubuntu. However, you will study Linux, and after training in our Center you can easily work with any Linux distribution: Debian, Mandriva, Red Hat, Mint, Alt Linux, Open SUSE, ASP Linux, MSVS and many others.

    The course program meets the requirements of the professional standard “Programmer”.

    Well " Linux (Ubuntu). Level 2. Programming in Linux in C» included in comprehensive training programs system administrators and Linux security specialists. By studying under a comprehensive program, you receive discount up to 15% for several courses included in the program at once. Each Comprehensive Linux Training Program Prepares for International Professional Certification

    Sandbox

    Barack Adama March 15, 2014 at 1:20 p.m.

    C++ training. What if you start on Linux?

    It's boiling!

    In the current school education system, the adaptation to the Microsoft operating system is amazing: with very rare exceptions, you can see something like Edubuntu or Russian ALT Linux somewhere, but otherwise it’s Windows. In my opinion, it is high time that schools introduce children to a different view of what the interface between man and hardware should be, and not look for common paths. Perhaps it is precisely this comparative-analytical view of things that will make it possible to raise the extremely low level of computer literacy among school graduates who cannot even format a text in Word or make a good presentation in PowerPoint.

    It is sincerely surprising that in schools it is considered extremely complex and even mystical to compose two-dimensional arrays in the same Pascal, which, by the way, is also high time to replace it with the more flexible and convenient Python or JavaScript. Dear teachers, what should be the motivation of a student if he teach in a dead language? We don’t learn Slavic first, and then Russian and others, to consolidate the rules of grammar?!

    Considering the fashionability of the programming profession and a certain romance in the minds of young people, inspired by Hollywood movies, people enter universities and are faced with a number of difficulties: their heads begin to expand sharply, which inevitably leads first to fatigue and then to disappointment in their choice. The fact remains: if you associate yourself with a profession that requires constant self-improvement, then start doing this even before entering. There are many materials that will help you be more prepared during your studies and will allow you to find a job in your specialty by the 3-4th year of study. Move!

    Against the backdrop of such reasoning, someone came to me to make a short tutorial on how to write, compile and run a program in C++ on Linux without special tools (IDE). This approach will be able to introduce a novice programmer to the development process in the most trivial form, as well as to the Linux operating system, which is fundamentally new to him. At the end of my habrapost I will write a list of references and useful links.

    Let's start with what we need:
    -Linux distribution (let's take Ubuntu);
    -Installed g++ compiler;
    -Regular text editor (gedit);
    -Terminal;

    Let's go!

    1. Installation of Linux and necessary software.
    Download the Linux Ubuntu distribution image from the official website ubuntu.ru. I would also like to add that I do not recommend using Wubi. We do a normal installation either on our hard drive or in a virtual machine. We burn the image to disk using Nero or ImgBurn. We reboot and go into the BIOS, where we need to set the boot priority from the CD/DVD drive. Save the settings and exit. Boot from the disk and install the operating system. (More details will be in the link below). We have a text editor and a terminal by default. In order to install the g++ compiler, open a terminal using the combination alt+ctrl+T and enter: sudo apt-get install g++ . We will be asked to enter a password, enter it and press Enter. Ready.
    2. Create a cpp file.
    Open your home folder in the Nautilus file manager and at the same time open the terminal alt+ctrl+t. In it we write the command touch helloworld.cpp. The touch command will create a file with the name you want. Now you can minimize the terminal and focus on Nautilus"e. Open our file and write the most popular code in the world:

    #include using namespace std; int main())( cout<< "Hello world!"; return 0; }

    Close and save.

    3.Compilation and launch.
    Open the terminal again and call our compiler with the command g++ -lm -o output helloworld.cpp . g++ is our compiler itself, and -lm and -o are the key parameters with which we launch it. output - having an output file where the result of our compilation is placed and followed by the name of our cpp file. Press enter, if the program is correct, then there will be no messages. Now, to run the program, enter the following in the terminal: ./output and press enter. The result “Hello world!” is displayed on the screen.
    So you've written your first C++ program for Linux! I congratulate you and wish you success in diversified and high-quality education. Your competence is in your hands, remember this.

    P.S. If at least one student does what I wrote, I will consider that my mission is completed. All the best!
    P.S.S. Links.

    It became clear that the topic was very relevant. Some errors and questions were taken into account, and as a result, a decision was made to hold a second master class. Added and corrected!

    Master class on C programming under Linux. We study the main API.

    This master class is intended for people who want to learn the *nix API of similar operating systems, in particular for Linux. Here we will look at the features of development for Linux OS, which include:


    • Familiarization with the process of building software and the specifics of the C compiler from GCC

    • Development and use of shared libraries

    • Debugging programs

    • Exploring low-level file I/O mechanisms

    • Studying mechanisms for multitasking and interprocess communication

    • Using file and network sockets

    • Study and Application of the Signal Mechanism

    • Studying processes, threads, their differences, using multithreading, studying thread synchronization mechanisms and their problems

    • Creating Daemons, Learning the Differences Between Daemons and Application Software

    • Exploring the features of console I/O

    • Applying and using memory-mapped files

    This master class is intended primarily for software developers, engineers, programmers and simply amateurs who are interested in the device and specifics of the Linux OS.

    Requirements for master class participants: Knowledge of the C language, at book level B.V. Kernighan, D.M. Richie "LANGUAGE C".

    The cost of this master class will be 6,000 rubles.

    The venue is Moscow, in the premises of the Neuron Haxspace.
    Dates: Approximately July 4 (Monday), to July 7 (Thursday) from 10 to 17 with a lunch break and tea/coffee breaks.

    There are no plans for online broadcasts.
    Number of people in the group: 8-10.

    Registration is carried out by email [email protected] or in the comments to this post. Your full name is required to register. (in full) and contact information (phone number and email). It is advisable to describe the purpose of attending this master class, level of training and occupation.

    Detailed course program:

    Module 1. Introduction


    • Familiarization with the specifics of software assembly in GNU/Linux

    • Introduction to console text editors (vi, nano, mcedit)

    • Working with the gdb debugger

    • Manual and automatic software assembly (Makefile)

    • Client-Interface-Server (CIS) model

    • Static build of libraries

    • Shared Libraries

    • Working with Environment Variables

    Module 2: Low-Level I/O and File Operations

    • Overview of I/O mechanisms in Linux (Ubuntu)

    • File descriptors

    • System calls: open, close, write, read and lseek

    • File types

    • Inodes and Hard Links

    • File permissions

    • proc file system

    • Two ways to read the contents of a directory

    • Sparse files and the specifics of their use

    • Locking areas of a file

    Module 3: Interprocess Communication

    • Linux Interprocess Communication Mechanisms (Ubuntu)

    • Unnamed pipes

    • Named pipes

    • Messages queue

    • Shared memory

    • Semaphores

    Module 4: Sockets

    • Sockets in a file namespace (UNIX sockets)

    • Pair sockets

    • Network sockets

    Module 5. Signals

    • Introduction to Signals

    • How signals differ from other interprocess communication mechanisms

    • Specifics of signal handling

    • Module 6: Processes

    • Cloning processes - fork()

    • Replacing the executing process - exec()

    • Zombies - causes and ways to eliminate them

    Module 7: Streams

    • Threads and processes

    • Specifics of building multithreaded applications (multithreading)

    • Terminating a thread early

    Module 8. Streams (continued)

    • Creating a Thread Termination Handler

    • Synchronize primitives

    • Stream Attributes

    Module 9. Daemons (services)

    • The difference between a daemon and a console utility

    • Specifics of daemons development

    • Creating a daemon that uses network sockets

    Module 10. Console I/O

    • Specifics of console application development

    • Preventing Output Redirection

    • Terminal management

    • Hiding a user's password during authentication

    • Controlling the terminal using ESC sequences

    Module 11: Mapped Memory

    • Displaying a regular file

    • Share a file

    • Private mappings

    • Other uses of mmap

    Module 12. Homework

    • Specifics of developing 64-bit applications

    • Using the ncurses library

    Course leader: Sergey Dolin. Electronics engineer, Linux software developer (application software, test software for hardware, drivers). Software developer for embedded systems. Linux programmer since 2011. Worked at NICEVT OJSC, Concern Systemprom JSC, PROSOFT LLC (in the Dolamant subsidiary).

    All actions in the operating system are performed using programs, so many beginners are interested not only in using other people’s programs, but in writing their own. Many people want to contribute to the OpenSource codebase.

    This is a review article about programming for Linux. We will look at which languages ​​are used most often, consider the basic concepts and capabilities, we will look at how to write a simple program in one of the most popular programming languages, and how to manually assemble and run it.

    Historically, the Unix kernel was written in C. Moreover, this language was created for writing the Unix kernel. Since the Linux kernel was based on the Minix kernel (a version of Unix), it was also written in C. Therefore, we can say that the main programming language for Linux is C and C++. This trend continued for a long time.

    In general, you can write programs for Linux in almost any language, from Java and Python to C# and even Pascal. All languages ​​have compilers and interpreters. Writing programs in C++ is difficult, and C is considered obsolete by many, so many programmers use other languages ​​to write programs. For example, many system tools are written in Python or Perl. Most of the programs from the Linux Mint team, the Ubuntu installer and some apt scripts are written in Python. Many scripts, including simple optimization scripts, are written in Perl. Ruby is sometimes used for scripting. These are OpenShift scripts or, for example, the Metasploit framework. Some cross-platform program developers use Java. But the main components of the system are still written in C.

    We won't cover the basics of C in this article. C is a difficult language and you will need to read at least one book and practice a lot to master it. We will look at how to write C programs on Linux, how to compile and run them.

    Why learn C:

    2. Libraries

    Naturally, if you need to display a string or an image on the screen, you will not directly access the video card. You simply call a few functions that are already implemented in the system and pass them the data you want to display. Such functions are placed in libraries. In fact, libraries are collections of functions that are used by other programs. They contain the same code as in other programs, the only difference is that there is not necessarily the presence of an initialization function.

    Libraries are divided into two types:

    • Static- they are associated with the program at the compilation stage, they are associated and after that all library functions are available in the program as native ones. Such libraries have the extension .a;
    • Dynamic- such libraries are much more common; they are loaded into RAM and linked to the software dynamically. When a program needs a library, it simply calls it at a known address in RAM. This saves memory. The extension of these libraries is .so, which comes from Shared Object.

    Thus, for any C program you need to include libraries, and all programs use some kind of libraries. It is also important to note that no matter what language you decide to write in, in the end everything will be reduced to the C system libraries. For example, you write a program in Python, use the standard features of this language, and the interpreter itself is already a C/C++ program that uses system libraries to access the main features. Therefore, it is important to understand how C programs work. Of course, there are languages, like Go, that are immediately translated into assembler, but the same principles are used there as here. In addition, Linux system programming is mainly C or C++.

    3. Program build process

    Before we move on to practice and create our first program, we need to understand how the assembly process occurs and what stages it consists of.

    Every serious program consists of many files, these are source files with the extension .c and header files with the extension .h. Such header files contain functions that are imported into the program from libraries or other files.c. Before. How can the compiler build a program and prepare it for work, it needs to check whether all functions are actually implemented, whether all static libraries are available and assemble it into one file. Therefore, the first step is to run a preprocessor that assembles the source file, executing statements such as include to include the code of the header files.

    At the next stage, the compiler starts working, it performs all the necessary actions on the code, parses the syntactic structures of the language, variables and converts all this into intermediate code, and then into the code of machine instructions, which we can then look at in assembly language. The program at this stage is called an object module and is not yet ready for execution.

    Next, the linker gets to work. Its task is to link an object module with static libraries and other object modules. A separate object module is created for each source file. Only now the program can be launched.

    Now, let's look at this whole process in practice using the GCC compiler.

    4. How to build the program

    There are two types of compilers used to compile programs in Linux: . So far, GCC is more common, so we will consider it. Usually, the program is already installed on your system, but if not, you can install it on Ubuntu:

    sudo apt install gcc

    Before we move on to writing and assembling the program, let's look at the syntax and compiler options:

    $gcc options source_file_1.c -o finished_file

    Using options, we tell the utility what to do, what libraries to use, then we simply specify the source files of the program. Let's look at the options we'll be using today:

    • -o- write the result to a file for output;
    • -c- create an object file;
    • -x- specify the file type;
    • -l- load a static library.

    Actually, this is all the most basic thing we need. Now let's create our first program. It will display a line of text on the screen and, to make it more interesting, calculate the square root of the number 9. Here is the source code:

    include
    #include

    int main())(
    printf("website\n");
    printf("Root: %f\n", sqrt(9));
    return 0;
    }

    gcc -c program.c -o program.o

    This is the compilation stage, if there are no errors in the program, then it will be successful. If there are several source files, then this command is executed for each of them. Next we perform the linking:

    gcc -lm program.o -o program

    Pay attention to the -l option, with it we indicate which libraries need to be included, for example, here we include the library of mathematical functions, otherwise the linker simply will not find where this or that function is. Only after this you can run the program for execution:

    Of course, all these actions can be performed using various graphical environments, but by doing everything manually, you can better understand how everything works. Using the ldd command you can see which libraries our program uses:

    These are two loader libraries, the standard libc and libm, which we included.

    5. Assembly automation

    When we consider programming under Linux, it is impossible not to note the system for automating program assembly. The point is that when there are many source files for a program, you will not manually enter commands to compile them. You can record them once and then use them everywhere. There is a make utility and Makefiles for this purpose. This file consists of targets and has the following syntax:

    target: dependencies
    team

    The target dependency can be a file or another target, the main target is all, and the command performs the necessary build actions. For example, for our program the Makefile might look like this:

    program: program.o
    gcc -lm program.o -o program

    program.o: program.c
    gcc -c program.c -o program.o

    Then you just need to run the make command to start compilation, just remember to delete the previous temporary files and the compiled program:

    The program is ready again and you can run it.

    Conclusions

    Creating Linux programs is very interesting and exciting. You will see for yourself when you get a little used to this matter. It's difficult to cover everything in such a short article, but we've covered the very basics and they should give you the basics. In this article we looked at the basics of programming in Linux, if you have any questions, ask in the comments!

    C programming course for Linux:

    C is a fairly “ancient” programming language; it was formed in the early 70s. Despite this, C is a living language in the sense that it is actively used today. It was invented, used and is used to write significant parts of the program code of Unix-like operating systems. It is also used to write utilities, compilers, and, less commonly, application programs. That's why C is called a systems programming language.

    Its survivability can be explained by the fact that the operating principles of operating systems are relatively universal; they are not subject to the progress and diversity that can be observed in the environment of desktop and mobile software, and Web applications. C is not a very high level language, it is closer to computer architecture. As a result, C programs are compact and fast.

    C does not support object-oriented programming. OOP support is implemented in C++. Although the latter arose from the C language, it is not a “continuation” of it, but is a separate language that can be learned without knowing C. However, learning C is useful before getting to know its “advanced little brother”, because The syntax of the languages ​​is similar, C does not overload the brain of a novice programmer with superpowers and teaches him to understand the essence of what is happening.

    Is C good for getting into programming for the first time? If you are not studying at a university in a specialty related to IT, then no. C requires an understanding of the organization and operating principles of hardware, particularly memory. A lot of this is done with pointers, they play a key role; this topic is quite difficult to understand and is not usually studied in school.

    Of course, you can learn the basics of programming with C without having to learn pointers. However, a person will think he knows C without knowing much about it in substance. The C language was created by hardware-savvy professional programmers to write the UNIX operating system. It was not intended as a language for teaching beginners.

    Environments and compilers for C programming

    If you are using one of the GNU/Linux distributions, any text editor with syntax highlighting will do, you will also need GCC and a terminal.

    There are editors for programmers that include various add-ons, including a terminal, directory browsing, etc. For example, Geany or Atom.

    C is a compiled programming language. In GNU/Linux, to obtain executable files, GCC is used - a set of compilers, including a compiler for C. To obtain an executable file from a source file (usually such files have the *.c extension), you need to run a command in the terminal that looks something like this:

    gcc -o hello hello.c

    Where gcc is a command that launches a program that performs compilation and other actions; -o – a switch indicating that we manually specify the name of the executable file; hello – name of the resulting executable file; hello.c is the name of the source code file. The name of the executable file can be omitted:

    gcc hello.c

    In this case, the executable file will have the default name a.out.

    Windows has its own set of compilers - MinGW. It can be used on its own, but is included in the simple Dev-C++ development environment, which can be a good choice for learning to program in C and C++.

    When saving, select the file type "C source files (*.c)". The program is compiled and launched by pressing the F9 key. After execution, the program closes immediately and the result cannot be seen. To prevent this from happening, write two additional lines: #include and getch(). (This may not be relevant for a newer version of Dev-C++.)

    "Hello World" in GNU/Linux:

    #include \n") ; }

    "Hello World" on Windows:

    #include #include int main() (printf("Hello World \n") ; getch(); )

    On the other hand, there are a large number of cross-platform development environments. For example, Eclipse + CDT module, KDevelop, CLion. The latter is paid, produced by JetBrains, a leader in IDE development, but has a 30-day trial period, which may be enough for training. CLion is more convenient than other IDEs.

    "Hello World" in C

    Using the example of a simple program, we will immediately note some features of the C programming language.

    In the C language, the main() function takes on the role of the main branch of the program. This function must always be present in a complete C program, and program execution begins with it. However, the variables declared inside it are not global; their scope extends only to main(). However, in the C programming language, almost all program code is contained in a function, and the main() function is the main and required one.

    By default, the main() function returns an int data type, so you don't have to specify a return type. However, the compiler issues a warning in this case.

    The printf() function is designed to print data. Its purpose is similar to the write() procedure in Pascal and the print() function in Python. The printf() function does not break to a new line after printing. Therefore, a special character is used for the transition, which is denoted by the combination \n. Complete C expressions are separated by semicolons.

    In C, I/O functions are not part of the language. For example, in Python we do not need to import any module to use the print() and input() functions. In C, we cannot simply call the printf() function, because C itself simply doesn't have it. This function, as well as a number of others, can be enabled using the stdio.h header file. This is precisely why the line is written at the beginning of the program #include . Include is translated from English as “turn on”, and stdio is an abbreviation for “standard input-output”.

    Header files (they end in *.h) usually contain declarations of certain functions. A declaration is simply a description of a function: what parameters it takes and what it returns. The function code itself (definition) is not located in the header file, but in libraries (other files), which may already be compiled and located in system directories. Before compiling a program, the C language preprocessor is launched. Among other things, it includes at the beginning of the program file the contents of the header files specified in it.

    Practical work

    Comment out the first line of HelloWorld code. Try compiling the program. Were you able to obtain the executable file? What warning did the compiler give?

    1 // - one-line comment in C language; /* … */ - multiline comment in C language.