Как программировать на c на linux
Перейти к содержимому

Как программировать на c на linux

  • автор:

GCC Linux C compiler and C language hello world programs

The Linux gcc command is a C language complier that is right there to work with if one wants to get into C programing in a Linux system. I took a moment to start playing around with it, and just have some fun with a few quick, basic, C language hello world programs.

I am very much a javaScript developer, and as such I have been shying away from C for a long time. There is much about the language that strikes me as being very intense and time consuming. In javaScipt I like having things going on like garbage collection, and dynamic typing. Sure javaScript is like riding a bike with training wheels, but it is still very much a bike that will take me places. I have this mindset that what matters most in programing are things that are independent of language. Regardless if a program is written in javaScript, C, or even something like qBasic what does the program do? Why would I or anyone else want to use it? The answers to those questions are what matter first and for most to me.

However getting back to the topic at hand. I want to start experimenting with at least a few languages outside of javaScript, I still like the language a lot, it is still my preferred language by far, however I want to expand at least a little way into some other languages. With that said C has been on my scope for a long time, and I thought that it could not hurt to work out at least a few quick hello world C examples that I would then build using the Linux gcc command. So lets get to it then.

1 — Linux gcc and C Hello World

In this section I will be going over a very basic Hello world C language source code file called hello.c. This source code file is just a very simple typically hello world program that will just print Hello World to the standard output of the console. I then also worked out a simple bash script that will use gcc to build the hello.c file into a binary called just simply hello. I can then run the binary in the bash shell and get the expected result.

When it comes to learning any language one has to start somewhere, and this type of program is just that.

1.1 — The hello.c file

Here is the source code that I cam up with by just searching for a simple C language hello world program. It makes use of just one library called stdio.h which provides the printf function along with many other useful basic tools when it comes to working with standard output.

1.2 — The build.sh script

I then made a simple bash script that when called should build the hello.c file into a binary called just hello. In Linux systems binaries often seem to have no file name extension like that.

1.3 — Building my first C Programe with gcc

So when I run my build.sh script gcc compiles by hello.c into a hello binary. When I call my hello binary i end up getting the expected result in my console.

Well that was fun actually, it may just be a hello world program but it was fun to build a very simple yet functioning C binary. I should take a moment to look into making at least a few more C examples though, maybe sticking to what there is to work with in the stdio.h lib. Maybe even touch base on a few other features of gcc in the process, if I get to it.

2 — Printing an init value, and an improved build.sh

I should take at least one or two more steps beyond just a simple hello world example with this, just printing hello world to the console alone is not a good stopping point for me at least. I may or may not get into writing a collection of posts on C programing, but without even going that far there is the question of what the next step is from hello world. For me it seems like that next step is how to go about printing a number rather than a string to the console.

In javaScript doing so is just as simple as printing a string more or less, javaScript is a typeless language after all. However that is not the case with c of course I can not just pass an int for a parameter of a function where a string is what is expected.

2.1 — The print_int.c file

With C I am dealing with string typing, and with that said I can not just pass a number for an argument where a string is expected. Still doing so is not at all that much harder, in fact I can use the same printf method to do so by passing the init as a second argument and then using a pattern in the string that I pass as the first.

2.2 — Improved build.sh

For this example I made an improved build.sh script that will work not just with this source file, but any file that I want to build with gcc. With this script I am just making it so I can give one argument to the script that is the name of the C source file that I want to build. I am then also using the Linux cut command to just cut the file extension off the end of the file name to produce a name for the output file to create with Linux gcc.

2.3 — Looking good

So this example seems to work as it should for me also. The source file builds without any problems with gcc, and when I run the resulting binary I get the number printed out to the standard output.

So now I have worked out how to just print a string to the console, and now a number. The process is not so hard of course I can just stick to using just this one simple library that can eb used to just print things out to the standard output. There are a few more basic things that come to mind though that I should get to with this post, so lets look at some of the other methods in this basic c library.

3 — Fopen example

In the stdio there are also some basic functions for opening, writing to, and closing files. There is the fopen function, followed by fputs, and fclose to work with. These methods can be used to create a very basic hello world example that creates a file rather than spiting something out to the command line.

Once again I just need to use gcc to create a little binary, and then it does just what I thought it would.

These very simple hello world style C programs where fun. For someone that has been working with C for years, or decades even now these are of course trivial. However for me this is pretty cool coming from an experience where I have only been playing around with javaScript thus far.

4 — Conclusion

So this was fun to take a moment to play around with gcc for a little while. I was wondering to myself how hard could it be to just cerate a few very basic hello world style examples with the C language and build them with gcc? As I expected it was not so hard to do that at least when it comes to just some very simple examples.

The next step from here is to maybe start a collection of a few posts on creating a few simple programs written in C and compiled with gcc. I might get around to doing that at some point, if so I am sure I will end up editing, and expanding this post as needed. So far I have wrote just one more c code example for another post on the linux test command. In that post I made a simple c program that will check a given folder for markdown files and if one or more files are in there the program will end with a status of zero, else it will end with a non zero exit code status.

How to Write and Run a C Program in Linux

C is one of the world’s oldest, most widely-used programming languages. It has been used to develop countless applications, from operating systems to embedded devices. Even today, many developers still rely on C for its flexibility and reliability as a programming language.

The C Programming Language

C is a highly portable language. This means that programs written in C are easily transferable from one computer system to another without having to be rewritten from scratch. This allows developers to quickly port their applications across different platforms without too much extra effort or hassle.

Also, C offers an outstanding balance between high-level abstractions and low-level programming techniques. In other words, you can use pre-defined functions and libraries that handle more complex tasks like memory management or string manipulation while still being able to access the machine’s hardware directly if needed. This makes it suitable for almost any application ranging from large commercial projects to smaller hobby projects!

C has been around for over 40 years, so plenty of resources are available online and offline that provide helpful tutorials and detailed documentation on how best to use the language. Whether you’re just starting with programming or already an experienced programmer looking for some tips – you should have no trouble finding what you need when looking into C development!

Finally, unlike many other modern programming languages, C isn’t tied to just one platform or software framework – it can be used with almost every major Operating System (OS), including Windows, macOS, Linux, and even Android! This universality makes it an extremely versatile option compared to other languages, which may only be ideal for certain OSes or environments.
C is truly one of the most significant programming languages ever created, and its popularity doesn’t seem like it will diminish anytime soon! With its flexibility, portability, and ease of use – it’s no wonder why so many people choose this powerful language when building their software projects!

Install C Compiler (GCC) on Linux

We have run the steps and commands mentioned in this article on an Ubuntu 22.04 LTS system, but it works the same on other versions like Ubuntu 20.04 or Debian 11.

To compile a simple C program, we use the Linux command-line tool, the terminal. To open the terminal, you can use the Ubuntu Dash or the key combination Ctrl+Alt+T.

Install the build-essential packages

In order to compile and execute a C program, you need to have the essential packages installed on your system. Enter the following command as root in your Linux Terminal:

Install gcc compiler that is part of build-essential package with apt

You will be asked to enter the root password; the installation will begin after that. Please make sure that you are connected to the internet.

Write a simple C program

After installing the essential packages, let us write a simple C program.

Open Ubuntu’s graphical Text Editor and write or copy the following sample program into it:

Then save the file with .c extension. In this example, I am naming my C program as sampleProgram.c

Example C program

Alternatively, you can write the C program through the Terminal in gedit as follows:

This will create a .c file to write and save a program.

Compile the C program with GCC Compiler

In your Terminal, enter the following command to make an executable version of the program you have written:

Compile source code with gcc

Make sure your program is located in your Home folder. Otherwise, you will need to specify appropriate paths in this command.

Run the program

The final step is to run the compiled C program. Use the following syntax to do so:

Start our compiled C program

You can see how the program is executed in the above example, displaying the text we wrote to print through it.

This article taught you how to write, compile and run a simple C program in Linux. All you need is the essential packages and skills to make you a programming guru in Linux!

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7d99e4c6bce52313 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Getting started with C programming on Linux

A programmer’s job typically involves writing a program, compiling, executing and debugging. This article helps any newbie to get started C programming language, including setting up the system for programming, the compilation process and execution mechanism.

Getting started with CGetting started with C

Setting up the system

Learning C programming language on Linux based system is recommended. I use Ubuntu Linux Desktop for programming. Setting up the system typically involves installing editor, compiler and other programming tools if you have Ubuntu OS already installed. Otherwise install the Ubuntu OS.

Install editor, compiler and other tools

Enter the following command in the terminal to install tools.

Vim is a terminal based editor. build-essential package consists of gcc , g++ , make utility and Gnu C library.

Compiling and executing Hello World! program

Run the following command in the terminal to open the file helloWorld.c with vim editor.

Write the following program in that file and save it.

Compile the program by running the following command

Above command generates a binary called helloWorld. Execute the binary by running the following command.

This should print the Hello World! output.

Behind the scenes of compilation

The process of compilation involves the following steps.

  • Preprocessing
  • Generating assembly code (Called compilation proper)
  • Assembly
  • Linking

Preprocessing

A preprocessing step by compiler includes macro substitution, inclusion of other source files, removal of comments and conditional compilation.

Consider the following program,

File : hello_new_world.c

Run the preprocessor on the above file and save the output in a separate file. We can use the following command.

The output file hello_new_world.i has #include <stdio.h> replaced with the stdio.h file content; removed comments; removed some lines of code from the main function based on conditional compilation (if HELLO_NEW_WORLD is defined first puts will be processed or the other one) and substituted the macro HELLO_NEW_WORLD macro with its value «Hello New World!» (please check the last lines of following file).

File : hello_new_world.i

Generating assembly code

The C code in the above file hello_new_world.i can be converted into assembly by the follwing command.

The output file hello_new_world.s has the assembly code

Assembly

This part converts the assembly file into relocatable object file (which is in ELF format).

At this point, this object file consists of following sections.

  • .text — Program code
  • .data — Initialized global variables
  • .bss — Uninitialized global variables (Block storage start)
  • .rodata — Read only data such as format strings, string constants
  • Other custom fields.

Run the following command to see above sections.

The .text, .bss and .rodata contain functions, global variables and format stirngs mapped to addresses starting with 0. These addresses can be relocable when linked with other relocatable objects to form final binary executable. The linking step is explained below clearly.

Linking

The Linker’s job can be explained clearly with multiple source files.

Let’s assume the files a.c and b.c.

File: a.c

File: b.c

We can generate object files directly for a.c and b.c using following commands

We will use a tool called nm to check whether the functions (symbols) are defined in .text section of object file or not.

T indicates that the corresponding function is defined in .text section. U represents that the symbol is undefined. Here print_sqrt_random is undefined because the definition is in b.o object file.

Here print_sqrt_random is defined in the .text section of b.o object file. And printf , rand and sqrt symbols are undefined because the definitions are defined in the libc and math libraries.

The linker’s job is to link these object files with the libraries.

Static linking

Static linking object files and static librariesStatic linking object files and static libraries

Let’s create a final executable with the following command.

In the above command a.o and b.o are linked with static libraries libc.a and libm.a.

Let’s check whether rand, printf and sqrt symbols are defined in the final executable.

As you can see here rand, __sqrt and __printf symbols are defined in .text section of c_static final executable.

In the case of static linking , the symbols are defined in the final executable before execution itself.

Let’s check the size of the c_static.

Dynamic linking

Dynamic linking of shared librariesDynamic linking of shared libraries

Let’s create the final executable by linking a.o, b.o with the dynamic libraries (also called shared object files).

Let’s check whether rand, printf and sqrt symbols are defined in the final executable.

As you can see all the symbols are undefined ( U ). These symbols are linked during run time.

Let’s see the size of c_dynamic executable file.

The size of the dynamically linked executable file much lesser than the statically linked executable. The reason for this is the symbols are not defined in the dynamically linked executable.

Behind the scenes of execution

What happens when you execute the binary c_static or c_dynamic in the shell?

To execute the binary, we run it in the shell prompt like following.

The shell reads the input and invokes the system call execve() to create a new process for this binary execution. Remember, shell is just an application program like any other.

The execve() is called loader and is responsible for allocating stack, heap and data segments in the memory for this process. It also copies .data, .text section from the executable into memory and transfers the control to the beginning of the program. That means all static or global/extern variables are initialized before the program execution itself.

We will use a command called ldd to see the dependent libraries of c_dynamic.

The above information is placed in the c_dyamic by linker during the linking stage so that the loader knows which libraries have these functions defined in and which runtime linker to use.

The loader then loads the dependent shared libraries libm.so and libc.so into memory.

The library /lib64/ld-linux-x86-64.so.2 in the above command is runtime linker and links the undefined symbols printf, sqrt and rand with the definitions present in shared libraries during run time — before the program execution.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *