- Язык C, C++: как подключать (#include) заголовки относительно корня проекта в GCC, кроссплатформенно?
- Как добавить пути include и lib для настройки/создания цикла?
- 3 ответов:
- How to add include and lib paths to configure/make cycle?
- 3 Answers 3
- What are the GCC default include directories?
- 4 Answers 4
- How to add compiler include paths and linker library paths for newly installed Boost?
- 4 Answers 4
Язык C, C++: как подключать (#include) заголовки относительно корня проекта в GCC, кроссплатформенно?
Никак не могу понять простую вещь.
Мне необходимо подключать заголовочные файлы относительно корня проекта. Надоело указывать относительные пути, потому что из разных каталогов проекта путь до одно и того же заголовка будет разный. Да и вообще относительные пути — это неправильно.
Насколько я выяснил, в Linux можно добавлять в переменную окружения INCLUDE_PATH путь к каталогу проекта. После чего будут работать директивы #include с файлами относительно корня проекта:
. препроцессор последовательно перебирает пути в INCLUDE_PATH начиная с первого. Относительный путь из директивы include разрешается относительно (sic) папки из INCLUDE_PATH. Если файл не найден, переходим к следующему элементу INCLUDE_PATH. Если INCLUDE_PATH исчерпан, компилятор сообщает об ошибке.
Однако возникают вопросы.
1. Какой путь добавлять к INCLUDE_PATH? Относительно корня файловой системы? Но тогда проект не будет собираться в другом каталоге, например, когда пользователь захочет самостоятельно скомпилировать проект, ведь у него не будет установлен нужный каталог в INCLUDE_PATH.
2. Где и как прописывать INCLUDE_PATH? Я поковырял исходники (Makefile) нескольких C/C++ опенсорчных проектов и не нашел никакой работы с INCLUDE_PATH. Значит, делают как-то по-другому, но как?
3. Проект кроссплатформенный. Необходимо понять, как и где настраивать INCLUDE_PATH (предположим, что используется система сборки make), чтобы компиляция шла и в Linux и в Windows под GCC.
4. Проект кроссплатформенный на Qt4. Необходимо понять, как и где настраивать INCLUDE_PATH, чтобы компиляция шла и в Linux и в Windows под GCC.
Источник
Как добавить пути include и lib для настройки/создания цикла?
Мне нужно место для установки библиотек в поле linux, к которому у меня нет доступа su. Я использую
/local [/bin,/lib, / include], но я не знаю, как я могу сказать ./ настроить поиск библиотек там (в частности, я пытаюсь скомпилировать emacs, который нуждается в libgif, который не входит в мой дистрибутив).
Я пробовал добавлять
to .bashrc, но это, кажется, не работает.
3 ответов:
вы хотите конфиг.файл сайта. Попробуйте:
всякий раз, когда вы вызываете сгенерированный autoconf сценарий настройки с —prefix=$HOME/local, конфигурация.сайт будет прочитан и все задания будут сделаны за вас. CPPFLAGS и LDFLAGS должны быть все, что вам нужно, но вы можете сделать любые другие желаемые назначения, а также (следовательно . в приведенном выше примере). Обратите внимание, что я флаги принадлежат добейтесь того, и не в уровне, а я предназначен для предварительной обработки и не компилятор.
установить с CFLAGS и LDFLAGS, когда вы запустите Make:
Если вы не хотите делать это миллион раз, экспортируйте их в свой .bashrc (или свой эквивалент). Также установите LD_LIBRARY_PATH для включения /home / me / local / lib:
это заняло некоторое время, чтобы получить право. У меня была эта проблема при кросс-компиляции в Ubuntu для цели ARM. Я решил ее с помощью:
обратите внимание CFLAGS не используется с autogen.sh/configure, используя его дал мне ошибку:»configure: error: C компилятор не может создавать исполняемые файлы». В среде сборки я использовал autogen.sh сценарий был предоставлен, если у вас нет autogen.sh сценарий замены ./autogen.sh С./ настройка В приведенной выше команде. Я запустил конфиг.думаю на целевая система для получения параметра —host.
после успешного запуска autogen.sh/configure, скомпилировать с помощью:
CFLAGS, которые я выбрал для использования, были: «- march=armv5te-fno-tree-vectorize-mthumb-interwork-mcpu=arm926ej-s». Потребуется некоторое время, чтобы правильно настроить все каталоги include: вы можете захотеть, чтобы некоторые из них указывали на ваш кросс-компилятор, а некоторые указывали на вашу корневую файловую систему, и, вероятно, возникнут некоторые конфликты.
Я уверен, что это не идеальный ответ. И я все еще вижу некоторые каталоги, указывающие на / и не /ccrootfs в Makefiles. Хотелось бы знать, как это исправить. Надеюсь, это кому-то поможет.
Источник
How to add include and lib paths to configure/make cycle?
I need a place to install libraries in a linux box I have no su access to. I’m using
/local[/bin,/lib,/include], but I don’t know how can I tell ./configure to look for libraries there (particularly, I’m trying to compile emacs, which needs libgif, which doesn’t come in my distro).
to .bashrc but it doesn’t seem to work.
/local/include:$C_INCLUDE_PATH , your compiler will search firstly in
/local/include , and in $C_INCLUDE_PATH only if it didn’t found the include in the first directory.
3 Answers 3
You want a config.site file. Try:
Whenever you invoke an autoconf generated configure script with —prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the . in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.
Set LDFLAGS and CFLAGS when you run make:
If you don’t want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:
/Descargas/emacs-23.3$ LDFLAGS=»-L/home/tneme/local/lib» CFLAGS=»-l/home/tneme/local/include» ./configure —prefix=»/home/tneme/local» checking build system type. i686-pc-linux-gnu checking host system type. i686-pc-linux-gnu checking for gcc. gcc checking whether the C compiler works. no configure: error: in /home/tneme/Descargas/emacs-23.3′: configure: error: C compiler cannot create executables See config.log’ for more details t
This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: «configure: error: C compiler cannot create executables». In the build environment I was using an autogen.sh script was provided, if you don’t have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the —host parameter.
After successfully running autogen.sh/configure, compile with:
The CFLAGS I chose to use were: «-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s». It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I’m sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
Источник
What are the GCC default include directories?
When I compile a very simple source file with gcc I don’t have to specify the path to standard include files such as stdio or stdlib.
How does GCC know how to find these files?
Does it have the /usr/include path hardwired inside, or it will get the paths from other OS components?
4 Answers 4
In order to figure out the default paths used by gcc / g++ , as well as their priorities, you need to examine the output of the following commands:
The credit goes to Qt Creator team.
There is a command with a shorter output, which allows to automatically cut the include pathes from lines, starting with a single space:
The credit goes to the libc++ front-page.
Though I agree with Ihor Kaharlichenko’s answer for considering C++ and with abyss.7’s answer for the compactness of its output, they are still incomplete for the multi-arch versions of gcc because input processing depends on the command line parameters and macros.
echo | /opt/gcc-arm-none-eabi-9-2019-q4-major/bin/arm-none-eabi-g++ -specs=nano.specs -mcpu=cortex-m4 -march=armv7e-m -mthumb -mfloat-abi=soft -x c++ -E -Wp,-v\ — -fsyntax-only yields
whereas echo | /opt/gcc-arm-none-eabi-9-2019-q4-major/bin/arm-none-eabi-g++ -x c++ -E -Wp,-v — -fsyntax-only yields
The former invocation utilizes newlib (see lines 1 and 3 of the output), the latter goes with the standard includes. The common files at the end of the list are an example for the usage of include_next .
Bottom line: Always consider all macros and compiler options when printing the include directories.
Источник
How to add compiler include paths and linker library paths for newly installed Boost?
I have RHEL 5.2, with Boost 1.33 installed. I downloaded boost_1_44_0.tar.bz2. and built it. On completion it showed:
- How do I add the above mentioned include paths?
- When I do «rpm -q boost», it shows boost-1.33.1-10.el5. Why is that so, when I’ve installed version 1.44?
- Is there a better way to install the latest version of Boost?
4 Answers 4
There are always three steps to install software on Linux systems:
- configure — «check»
- make — «build software in current directory»
- make install — «copy files to the systems so the other software can use this software»
You likely did the equivalent of make but did not do the equivalent of make install . You need to run
after running ./b2
Just add the paths to your .bashrc or .profile (or whatever floats your boat) like this:
First, I removed the existing boost rpm using
A message is displayed saying «error: «boost» specifies multiple packages»
(I don’t remember whether I typed ‘boost’ or ‘boost-1.33.1-10.el5’)
The packages with dependencies were shown. I did:
and so on and then did:
This erased boost completely from my system.
Then I extracted boost_1_44_0.tar.bz2 using tar -xvjf boost_1_44_0.tar.bz2 and ran bootstrap with:
Then ran bjam as:
That’s it! Boost got installed on my system, and I didn’t have to specify any of the linker options while compiling programs! Yay! Now the ‘rpm -q boost’ command shows that there is no package installed.
Источник