Introduction to the C programming language. Programming in C (C) on Ubuntu (Linux)

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, look at the basic concepts, as well as capabilities, and figure out how to write the simplest program in one of the most popular programming languages, how to manually build 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 ( Unix versions), then 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 random access memory. 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 assembly, 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 mathematical functions, otherwise the linker simply won’t find where this or that function exists. 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:

I already wrote about how to install a full-fledged SI and C++ compiler on Windows in the article:.

But these languages ​​are cross-platform, and many people use Linux not only as a home system, but also as a work tool. Plus, the percentage of Linux users has increased recently. And many of them want to learn to program. Therefore, today I will tell you how to install a C and C++ compiler on a Linux system.


If you use Windows but want to try Linux, then check out my articles on virtual work machine:.

So, Linux is installed, the Internet is connected. Open the console and enter the command to install compilers.
$sudo apt-get install gcc g++

That's all, the compilers are installed. Now all that remains is to check.
We go to the home folder and create a file hello.c, open it and write a simple program:

#include main() ( printf("Hello\n"); )

Then open the console and compile the script into a program:
$gcc hello.c -o hello

That's it, the hello program should appear in the folder. Now let's launch it.
$./hello

But programming in a simple notepad and compiling in the console is a special perversion. We need a more or less normal IDE for programming in C and C++ with a built-in compiler.

If you read my article, then you understand what I'm talking about. Yes, we will install Geany. It is an excellent development environment for many languages. Writing console programs in it is a pleasure.
Open the console and write:
$sudo apt-get install geany

We agree with the installation and wait for it to complete. Then we launch the program.

We open the same hello.c file in it and modify it a little, then click on the button that looks like a brick “Collect current file" and launch the red button "View or run the current file". And we will see a console window with the result.

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, sharpening under operating system Microsoft is amazing: with very rare exceptions you can see something like Edubuntu or Russian ALT Linux somewhere, but otherwise it is 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 computer literacy from school graduates who cannot even format text in Word or create 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 are they teaching in a dead language? To reinforce the rules of grammar, we don’t learn Slavic first, and then Russian and others. So what the hell?!

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 small tutorial on how to write, compile and run a program in C++ on Linux without special means(IDE). This approach will be able to introduce a novice programmer to the development process in the most trivial form, as well as to a fundamentally new operating system for him. Linux system. 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;

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 or on our HDD, either in virtual machine. We record from using Nero or ImgBurn the image to disk. 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 detailed information will be in the link below). Text editor, we have a terminal by default. In order to install the g++ compiler, open the 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 file manager Nautilus 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.

Many beginning coders are afraid
programming in Linux - no Windows simplicity
and visibility. However, it also exists for Linux
lots of visual aids
programming, and it's not just a Delphi clone.
Of course, they cannot become complete
replacing the same Visual Studio, but quite
help speed up the development process
programs.

NetBeans

One of the best IDEs. Intended for
working with Java, you can use it
develop not only cross-platform
Java programs, but also web applications, web services and
clients for them, J2ME programs, etc. Maybe
work on Windows, Linux, MacOS. The IDE is extensible
various plugins and addons, which can be
find on the website. At the same time, everything is free, then
eat for hayalva! In general - an indisputable number
one.

QT/KDevelop Designer

Another powerful development environment on
platform KDE and Gnome. Cross-platform C++
applications only go out on the road. For
non-commercial Qt programs can be
free to use, exists
for almost all distributions.

Visual Basic clone, and not only in design,
but also in language constructions. Perfect
tool for VB programmers who want
switch to Linux. Simple and convenient interface.
Access to all main databases - MySQL,
PostgreSQL, etc. Works on almost everyone
distributions.

WYSIWYG editor for creating web pages. In
Reminds me a lot of Macromedia editor or everything
the same FrontPage. Supports automatic
work with the site via FTP.

Python and Ruby IDE environment making
programming in the language is quite simple
and exciting. Written actually on
Python.

Eclipse is not an IDE at all, but a whole platform for
various applications. To standard
the delivery includes additional plugins for
Java language support (JDT) and development
plugins for Eclipse (PDE - Plugin Development Environment). For
work with other languages ​​should be
special plugins installed - in Eclipse
can work on almost any
accessible programming language. Another
the advantage also applies to
expandability: gigantic amount
utilities (especially for Java) now
also available as plugins for Eclipse,
for example Ant, JavaDoc, JUnit, JDepend, Check Style, Subversion.
So we don't have to give up
your version control system, from your
code quality checking programs, etc.
The third advantage is that Eclipse is
cross-platform environment, that is
there are versions for different
operating systems (which cannot
afford the same Visual Studio).

JDeveloper

Platform from Oracle - not open source,
however, it is still free. As is clear from
the names are still used cross-platform
Java. Uses Sun JDK for work, so
Oracle has no complaints about what is being created
programs, in theory, will not have it.

And finally, the visual control environment
projects for Gnome Desktop. No less useful
program for programmers than an IDE.

Name: Programming in C++ on Linux.

The book "Programming in C++ on Linux" is devoted to developing applications in C++ in the KDEvelop development environment. The author of the book provides a detailed description of the interactions between application components, covers the basics of working with the Qt Designer utility, and discusses dialog box controls and the classes for which they are created. The book teaches the concept of Document/View, creating application interface elements. Topics such as saving and restoring various information displayed on the screen, developing text editors, organizing multitasking in applications based on interacting processes, and working with class and function templates are also covered. As a conclusion, the author gives useful recommendations for creating a help system for the developed application. The book is intended for professional programmers.


The book is dedicated to creating applications written in C++ in the KDevelop development environment. A description of how application components interact is given. We consider working with the Qt Designer utility and describe the main controls used in dialog boxes, as well as the classes created to work with them. The reader is introduced to the Document/View concept and learns how to create application user interface elements. In addition, individual chapters cover the issues of displaying various information on the screen, saving and restoring it from a file, creating text editors, working with class and function templates, and organizing multitasking in an application based on interacting processes. Finally, recommendations for creating an application help system are provided.

Content:
Introduction
Who is this book for?
Book structure
Conventions adopted in this book
Hardware and software requirements
Chapter 1 Interaction of application components
Signals and receivers
Sending signals
Implementation of receivers
Implementation of the connection
Event Handling
Working with a window
Working with input focus
Using the mouse
Using the keyboard
Implementing drag and drop
Event filters
Synthetic events
Event Processing Sequence
Conclusion
Chapter 2 Dialog boxes and basic controls
Creating a Conversational Application
Creating a template application
Creating a preset dialog box
Completing the creation of the conversational application
Creating Custom Dialog Boxes
Creating a Tabbed Dialog Box
Creating a Wizard
Chapter 3 Control classes
List class
Classes of linear regulator and linear indicator
Working with Date and Time
Chapter 4 Application, Document, and View Classes
Multi-window Qt application
Document class
Presentation class
Application class
KDE multi-window application
Document class
Presentation class
Application class
Chapter 5 Creating User Interface Elements
Qt library user interface
Making changes to the menu
Working with the status bar
KDE Applications User Interface
Making changes to the menu
Customizing the Toolbar
Working with the status bar
Chapter 6 Displaying information on the screen
Drawing figures
Working with a brush
Redrawing a window
Synchronizing View Objects
Text output
Working with Bitmaps
Device-dependent bitmaps
Hardware-independent bit images
Chapter 1 Working with Document Files
Saving and restoring information in the application
Customizing Dialog Boxes
Making changes to the menu
Setting the working directory
Chapter 8 Working with text documents
Creating a simple text editor
Creating a more complex editor
Creating the KDE Editor
Chapter 9 Collection Templates and Classes
Templates
Template concept
Function Templates
Class Templates
Collection classes
Types of Collection Classes
Arrays
Linked lists
Maps
Other collection classes
Chapter 10 Implementing multitasking in an application
Process interaction
Creating a client for a simple server
Creating a More Complex Server
Creating a client
Some notes
Chapter 11 In-App Help
Forms for submitting reference information
Ways to access help
Methods of presenting reference information
Forms of information submission
Programming Context Help
Displaying hints
Displaying help information in the status bar
Getting information on a specific element
user interface
Command Help Programming
Qt Application Command Help File Format
Creating a demo Qt application
Appendix 1 What's on the CD
Appendix 2 Internet Resources
Subject index


Download the e-book for free in a convenient format, watch and read:
Download the book Programming in C++ on Linux - Nikolay Sekunov - fileskachat.com, fast and free download.

Download pdf
Below you can buy this book at the best price with a discount with delivery throughout Russia.