Include linux compiler gcc h

linux/compiler-gcc6.h: No such file or directory #2762

Comments

aleisterdev commented Sep 5, 2016

Please describe your issue:

I get en error about a missing gcc6.h when compiling

If known, describe the steps to reproduce the issue:

When arrived to the command:
$ make-kpkg —rootcmd fakeroot kernel_image kernel_headers

In file included from include/linux/compiler.h:54:0,
from include/uapi/linux/stddef.h:1,
from include/linux/stddef.h:4,
from ./include/uapi/linux/posix_types.h:4,
from include/uapi/linux/types.h:13,
from include/linux/types.h:5,
from include/linux/page-flags.h:8,
from kernel/bounds.c:9:
include/linux/compiler-gcc.h:107:30: fatal error: linux/compiler-gcc6.h: No such file or directory
#include gcc_header(GNUC)
^
compilation terminated.
Kbuild:35: recipe for target ‘kernel/bounds.s’ failed
make[3]: *** [kernel/bounds.s] Error 1
Makefile:1006: recipe for target ‘prepare0’ failed
make[2]: *** [prepare0] Error 2
make[2]: Leaving directory ‘/home/kali/kernel’
debian/ruleset/targets/common.mk:194: recipe for target ‘debian/stamp/conf/kernel-conf’ failed
make[1]: *** [debian/stamp/conf/kernel-conf] Error 2
make[1]: Leaving directory ‘/home/kali/kernel’
/usr/share/kernel-package/ruleset/minimal.mk:93: recipe for target ‘debian/stamp/conf/minimal_debian’ failed
make: *** [debian/stamp/conf/minimal_debian] Error 2
Failed to create a ./debian directory: No such file or directory at /usr/bin/make-kpkg line 970.

But of course:
(kali-rolling)kali@localhost:

/kernel$ sudo apt-get install gcc-6 g++-6
Reading package lists. Done
Building dependency tree
Reading state information. Done
g++-6 is already the newest version (6.1.1-11).
g++-6 set to manually installed.
gcc-6 is already the newest version (6.1.1-11).
gcc-6 set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

That’s not the first time that I had this issue, I had it also when compiling the drivers for my wifi adapter.
Can someone help me with this please?
I’m compiling the kernel headers:
3.18.0-12320-gf988d48
That’s the version I have on: $ uname -r
3.18.0-12320-gbb6b499

I know that the last bit is different and not sure if it matters.
The commit for that kernel was found with:
kali@localhost: /kernel$ git checkout HEAD 675

Any other number different from 675 would have changed the «12320» part of the kernel version.

The text was updated successfully, but these errors were encountered:

Источник

Установка GCC в Ubuntu

Большинство программ в Linux написаны на C или С++, и если вы хотите собирать их из исходников, то вам обязательно понадобиться компилятор, также он понадобиться, если захотите начать писать свои программы на одном из этих языков.

Существует два основных компилятора в Linux — это GCC и Clang, они похожи по своим возможностям, но так сложилось, что первый считается стандартом для Ubuntu. GCC расшифровывается как GNU Compiler Collection. В этой статье мы рассмотрим, как выполняется установка GCC в Ubuntu, а также рассмотрим базовые приемы работы с этим набором программ в терминале.

Набор компиляторов GCC

Все программы представляют собой набор машинных команд, которые выполняются процессором. Эти команды — последовательность бит. Но писать программы наборами бит очень неудобно, поэтому были придуманы языки программирования высокого уровня. Код на языке программирования хорошо читаем и понятен для человека, а когда из него нужно сделать программу, компилятор ubuntu преобразует все в машинные команды.

Читайте также:  Windows into the earth

В базовую поставку компилятора входят такие программы:

  • libc6-dev — заголовочные файлы стандартной библиотеки Си;
  • libstdc++6-dev — заголовочные файлы стандартной библиотеки С++;
  • gcc — компилятор языка программирования Си;
  • g++ — компилятор языка программирования C++;
  • make — утилита для организации сборки нескольких файлов;
  • dpkg-dev — инструменты сборки пакетов deb.

Все эти пакеты являются зависимостями пакета build-essential, поэтому для установки всего необходимого достаточно установить этот пакет.

Установка GCC в Ubuntu

Если вас устраивает текущая версия GCC, которая есть в официальных репозиториях дистрибутива, то вам достаточно установить пакет build-essential. Для этого выполните команду:

sudo apt -y install build-essential

После завершения установки все необходимое для компиляции программ будет установлено. И вы сможете использовать компилятор. Рассмотрим версии и расположение файлов компилятора:

whereis gcc make

Если необходима более новая версия компилятора, например, на данный момент последняя версия — 11, то можно использовать PPA разработчиков с тестовыми сборками. Для добавления PPA в систему выполните команды:

sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test && sudo apt update

Далее установите сам компилятор:

sudo apt -y install gcc-snapshot && sudo apt -y install gcc-11g++-11

Это не заменит ваш текущий компилятор на новый. В системе просто появятся 2 версии компиляторов gcc-11 и g++11, которые вы можете использовать для своих программ. Это лучший вариант на данный момент, но если вы хотите все же сделать gcc-9 компилятором по умолчанию, выполните:

sudo update-alternatives —install /usr/bin/gcc gcc /usr/bin/gcc-9 60 —slave /usr/bin/g++ g++ /usr/bin/g++-9

Готово, теперь вы можете проверить версию gcc-6:

Установка GCC в Ubuntu завершена, и можно переходить к сборке программ. Для удаления компилятора достаточно удалить пакет build-essential при помощи команды:

sudo apt purge -y build-essential && sudo apt-y autoremove

Использование GCC в Ubuntu

Рассмотрим пример компиляции минимальной программы hello.c для освоения работы с gcc. Вот код программы, откройте любой текстовый редактор и сохраните его в файле с названием hello.c:

#include
int main(void) <
printf(«Hello, world!\n»);
return 0;
>

Теперь запустим сборку программы:

Когда сборка программы будет завершена, на выходе появится файл с названием a.out. a.out –это имя исполняемого файла, которое по умолчанию, сгенерировано при помощи gcc. Далее можно запустить данный файл:

Готово, компилятор прекрасно работает в системе, и теперь можно писать свои программы или собирать чужие.

Выводы

В этой статье мы рассмотрели, как установить gcc в Ubuntu 20.04, это один из самых популярных компиляторов для этой операционной системы. И устанавливается он очень просто, если у вас остались вопросы, спрашивайте в комментариях!

На завершение видео с демонстрацией самого процесса:

Источник

How To Compile And Run a C/C++ Code In Linux

I am a new Linux user and student who used to write C or C++ programs on MS-Windows. Now, I am using Ubuntu Linux. How can I compile a C or C++ program on Linux operating systems using bash Terminal application?

To compile a C or C++ program on any Linux distro such as Ubuntu, Red Hat, Fedora, Debian and other Linux distro you need to install:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements GNU C/C++ compiler
Est. reading time 2 minutes
  1. GNU C and C++ compiler collection
  2. Development tools
  3. Development libraries
  4. IDE or text editor to write programs

If you are using Fedora, Red Hat, CentOS, or Scientific Linux, use the following yum command to install GNU c/c++ compiler:
# yum groupinstall ‘Development Tools’
If you are using Debian or Ubuntu Linux, type the following apt-get command to install GNU c/c++ compiler:
$ sudo apt-get update
$ sudo apt-get install build-essential manpages-dev

Step #2: Verify installation

Type the following command to display the version number and location of the compiler on Linux:
$ whereis gcc
$ which gcc
$ gcc —version
Sample outputs:

Fig. 01: GNU C/C++ compilers on Linux

How to Compile and Run C/C++ program on Linux

Create a file called demo.c using a text editor such as vi, emacs or joe:

How do I compile the program on Linux?

Use any one of the following syntax to compile the program called demo.c:

In this example, compile demo.c, enter:

If there is no error in your code or C program then the compiler will successfully create an executable file called demo in the current directory, otherwise you need fix the code. To verify this, type:
$ ls -l demo*

How do I run or execute the program called demo on Linux?

Simply type the the program name:
$ ./demo
OR
$ /path/to/demo
Samples session:

Animated gif 01: Compile and run C and C++ program demo

Compiling and running a simple C++ program

Create a program called demo2.C as follows:

To compile this program, enter:

To run this program, type:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How do I generate symbolic information for gdb and warning messages?

The syntax is as follows C compiler:
cc -g -Wall input.c -o executable
The syntax is as follows C++ compiler:
g++ -g -Wall input.C -o executable

How do I generate optimized code on a Linux machine?

The syntax is as follows C compiler:
cc -O input.c -o executable
The syntax is as follows C++ compiler:
g++ -O -Wall input.C -o executable

How do I compile a C program that uses math functions?

The syntax is as follows when need pass the -lm option with gcc to link with the math libraries:
cc myth1.c -o executable -lm

How do I compile a C++ program that uses Xlib graphics functions?

The syntax is as follows when need pass the -lX11 option with gcc to link with the Xlib libraries:
g++ fireworks.C -o executable -lX11

How do I compile a program with multiple source files?

The syntax is as follows if the source code is in several files (such as light.c, sky.c, fireworks.c):
cc light.c sky.c fireworks.c -o executable
C++ syntax is as follows if the source code is in several files:
g++ ac.C bc.C file3.C -o my-program-name
See gcc(1) Linux and Unix man page for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

thank you so much ur solution gave a relief…
it made my gcc command to work

Very nice article…..

In Fig. 01, you did “whereis” twice. Shouldn’t it be “which” the second time? Thanks for the tut though. Big fan!

Another mistake, please change the following comment:
## assuming that executable-file-name.c exists ##
to
## assuming that program-source-code.c exists in the current directory ##

how to compile a program that use math functions and other things?

For the sake of supplying an example, let’s say you want to use the cosine function. This is supplied in the Linux math library. The cosine function is called ‘cos()’. Similarly, the sine function is called ‘sin()’.

First, to find information about how to use them, type “man cos” in a terminal session. This gives you the manual page for the cosine function. The output from ‘man’ may vary for your system, but it likely tells you three things: 1. first, include the math.h header, 2. cos() takes a ‘double’ as its argument and it returns a double as its output, 3. to build your program, tell the C compiler to include the math library (-lm).

Here’s a sample program that does all of this:

Love it!
Thank you. I have a trouble in doing step 1 and 2. But they are fixed.

thank u ,
need pdf of the commands guide to access the c/c++/java.

to compile and run a c++ program in ubuntu follow these simple steps:
1 open terminal window.
2 type “gedit” .
3 A gedit window will appear whereyou can write your program.
4 save your program as “filename.cpp” on desktop, “.cpp” is compulsory.
5 open terminal again and type “cd Desktop”.
6 In second line type “g++ filename.cpp”.
7 Type “./a.out”.
NOW YOUR WILL RUN.

very nice to your step.
thanks

Thanks! This article really helped me to find the GNU compiler in a Linux Operating System and showed me how to compile a C program.

dear sir,
what is the procedure to run .cpp program in linux distro debian 5 ?

just about to get around to learning c along with teaching my sons it. i had no idea where to start, the first page i checked is a bumper bonanza.

Источник

Читайте также:  Не удалось выполнить настройку windows
Оцените статью