Linux pkg config gcc

How to compile C and Gtk+ with GCC on Linux?

I’ve searched and searched but I’m not getting the information I really want. Can someone please explain, as completely and fundamentally as possible, how Gtk+ code is compiled when writing in C, using GCC, on Linux. There’s things like backticks, «c99», and .o files that I don’t understand at all. I’d also appreciate any resources for learning Gtk+ code. All the sources I’ve found are for versions 2.x, but I think 3.6 is the current version. I’d like to reiterate, I’m only interested in C code. Please don’t try explaining to me the benefits of C++ or C#, I’ve read all of them. I’m here for C. Thank you!

I’m afraid this question is overly broad and mixes different topics. Compiling C code on a Unix is a topic in itself. Compiling Gtk code is just a specific version of that activity. You probably should just pick up an introductory book on C. Compiling Gtk code will become obvious after that.

The question is perfectly valid, but I cannot believe someone cannot get this really basic information: google.com/search?q=compiling+gtk returns documentation for GTK+2 in the first line and for GTK+3 in the second one.

5 Answers 5

For starters, you write your C code, say «hello_world_gtk.c», and then you compile and link it against Gtk, by using appropriate compiler and linker flags. These flags are given to you by the pkg-config tool. To get the needed compiler flags, you call that tool with:

Читайте также:  Distro linux live usb

The backticks allow you to get the output from pkg-config and pass it on as arguments to gcc:

gcc `pkg-config gtk+-2.0 --cflags` hello_world_gtk.c -o hello_world_gtk `pkg-config gtk+-2.0 --libs`

But you’re not required to use backticks. You can just copy&paste the flags manually if you want.

For Gtk 3, replace «2.0» with «3.0». If pkg-config reports that it couldn’t find the package, then you didn’t install the Gtk development package as offered by your Linux distribution.

If you generally don’t understand how you compile something into object files and then link it, then you shouldn’t begin with Gtk, but with plain C instead. Once you’re familiar with the absolute basics of compiling and linking, then you can move on to Gtk applications.

I got it compiled and running, Something was wrong with my installation. Although I was only able to get 2.0 installed, not any 3.x version.

As others said, your question is overly broad. It asks about backticks (basic shell syntax), what «.o» files are (basic programming), and GTK programming (somewhat advanced programming).

But to answer it best I can, and assuming you just have a single source file, use

gcc -Wall -Wextra -std=c99 `pkg-config --cflags --libs gtk+-2.0` example.c -o example 

where «example.c» is the name of your source. Here’s the breakdown:

  • Use the flags «-Wall» and «-Wextra» so you can see all the warnings (and fix them).
  • Use the «std» flag to set your C dialect. There are several and gcc has either total or partial support for most of them. Read the man pages or info pages for more information. Using «c99» like above is not a bad choice.
  • And use pkg-config and command substitution (i.e., backticks) to set the libraries and includes. Notice you can do both at once, although a lot of people use it twice by two backticked versions of pkg-config. Backticks substitute the output from the command within the ticks. Try running the pkg-config within the backquotes by itself on the command line and you’ll see what it does.
Читайте также:  Установка flash player kali linux

Unfortunately, there aren’t many resources for 3.x GTK code and most of it is still 2.x based. You’ll just have to resort to either gtk mailing lists or the reference manual.

As for GTK 3.x, the reason you can’t compile for it is likely that your distribution is GTK 2.x based. Newer distributions may have GTK 3.x in their repos.

Источник

Русские Блоги

pkg-config может использоваться для вывода соответствующей информации о библиотеке, такой как путь к библиотеке, путь к связанным файлам заголовков и т. д. Это будет очень полезно при компиляции программы. Например, теперь вы хотите скомпилировать программу, которая зависит от библиотеки librtmp.so. Где найти librtmp.so связанные заголовочные файлы? Где находится библиотека librtmp.so? Это большая проблема, но ни одна из них не является проблемой с pkg-config. Сначала взгляните на следующую команду:

[email protected]:~$ pkg-config --cflags librtmp -I/usr/local/include [email protected]:~$ pkg-config --libs librtmp -L/usr/local/lib -lrtmp -lz -lssl -lcrypto

Видя, что pkg-config может найти путь к заголовочному файлу, он также может найти, где находится инвентарь, и также может узнать другие библиотеки, от которых он зависит.

С помощью pkg-config, когда я компилирую программу для использования библиотеки librtmp.so, я могу написать:

[email protected]:~$ gcc sample.c -o sample `pkg-config --cflags --libs librtmp`

Хахахаха, с pkg-config, маме никогда не придется беспокоиться о поиске библиотек, когда моя программа компилируется

Итак, возникает вопрос: откуда pkg-config узнает такую ​​информацию, как путь к инвентарю и файл заголовка?

Ответ находится в файле .pc. После того, как файл библиотеки скомпилирован, в каталоге будет создан каталог с именем pkgconfig, который содержит файл .pc связанной библиотеки. Этот файл содержит соответствующую информацию о модификации библиотеки. Чтобы найти и прочитать, необходимо установить файл .pc в каталог / usr / lib / pkgconfig / или добавить путь установки файла .pc в переменную среды PKG_CONFIG_PATH. Цель этого — позволить другим программам, которые зависят от этой библиотеки, автоматически связывать библиотеку с помощью pkg-config, избегая ошибок во время компиляции.

Читайте также:  Настройка файла подкачки линукс

Общие параметры pkg-config:

—list-all Вывести список всех установленных общих библиотек
—cflags Перечисляет флаги предварительной обработки и компиляции для указанной общей библиотеки.
—libs Перечисляет флаги ссылок для указанной общей библиотеки.

Переменная окружения PKG_CONFIG_PATH используется для указания пути, где pkg-config ищет файлы .pc. Кроме того, pkg-config также будет искать файлы .pc в каталоге / usr / lib / pkgconfig /.

Установите переменную среды следующим образом: export PKG_CONFIG_PATH = / usr / local / lib

Источник

Оцените статью
Adblock
detector