Recompile with fpic linux

Перекомпилируйте с параметром -fPIC, но этот параметр уже находится в make-файле

Я получаю эту ошибку, когда делаю make:

В нем говорится, что я должен перекомпилировать с параметром -fPIC . Я сделал это, добавив параметр -fPIC для CFLAGS и CXXFLAGS , но я все еще получаю ту же ошибку. Есть ли способ решить это? Я видел, что эта проблема связана с использованием 64-разрядной машины, и это правда, что я использую одну.

7 ответов

У меня была эта проблема довольно давно, и если я правильно помню, исправление перемещало расположение -fPIC сразу после gcc в командной строке. Совершенно бессмысленно, а теперь и меньше, но, насколько я помню, это исправлено.

Я столкнулся с той же проблемой, но у нее был дополнительный поворот. Ответ @clintm решил ее, но я подумал, что опишу свой вариант проблемы здесь для дальнейшего использования .

Makefile на 32-битной машине:

Это правильно скомпилировано. Но тот же Makefile не удался, когда я попробовал его на 64-битной машине. Я изменил «-fpic» на «-fPIC», и это все равно не удалось. Я изменил правило объекта на:

и все равно не получилось.

Наконец, я поместил «-fPIC» в фактическую переменную компилятора (так что теперь «-fPIC» появляется в правиле для каждого объекта и правило для общей библиотеки):

И это сработало!

если проект, который вы хотите скомпилировать, имеет правильный сценарий настройки, например, так:

так что весь флаг будет правилом Makefile .

За несколько дней до того, как мне понадобится старшая вер. VLC для компиляции на машине x64, у него есть хороший скрипт configure; -)

Допустим, у вас есть такой make-файл, как:

просто добавьте флаг -fPIC следующим образом:

и так далее с остальным make-файлом.

Я столкнулся с этой проблемой кросс-компиляцией с помощью цепочки инструментов android-ndk. В итоге мне пришлось использовать

Ни -fPIC , ни -fPIE для меня в этой ситуации.

Я кросс-компилировал shadowsocks-libev на компьютере с CentOS 7, со мной произошла та же проблема, она отлично работает на моем ноутбуке с

но на travis ci это не сработало, я должен добавить -fPIC к CC и CXX, чтобы заставить его работать

У меня возникла эта проблема после обновления gcc. У меня был один файл .o (sqlite), который не был очищен Makefile, и в результате у меня возникла эта проблема (при условии, что он был скомпилирован с более старой версией gcc). После удаления этого файла и восстановления эта ошибка исчезла.

Читайте также:  Изменить права доступа всей папки linux

Источник

Recompile with -fPIC ? #64

Comments

tianlaizhiyin commented Mar 24, 2016

Hi Aorimn,
Can you help me? When I install this program,the problem got me stumped。

/usr/bin/ld: /usr/local/lib/libmbedcrypto.a(aes.o): relocation R_X86_64_32S against `.bss’ can not be used when making a shared object;
/usr/local/lib/libmbedcrypto.a: could not read symbols: Bad value
collect2: ld 返回 1
make[2]: *** [src/libdislocker.so.0.6.1] 错误 1
make[1]: *** [src/CMakeFiles/dislocker.dir/all] 错误 2
make: *** [all] 错误 2

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

Aorimn commented Mar 25, 2016

It shouldn’t happen as the library is already built with -fPIC. Which linux distro have you? Which gcc/clang version? Can you run make clean && make VERBOSE=1 and paste it in order for me to help you debug this issue?

tianlaizhiyin commented Mar 28, 2016

Yeah, I can found it built with -fPIC, but it still does not run correctly.

Aorimn commented Mar 28, 2016

Indeed, but that doesn’t give me your compiler version ( /usr/bin/cc —version ) nor your linux distribution. Can you please provide them so that I can try to reproduce the error?

tianlaizhiyin commented Mar 28, 2016

Oh! Sorry, I forgot that. Is this version too old?

[root@JefServ dislocker-0.6.1]# cc —version
cc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16)
Copyright © 2010 Free Software Foundation, Inc.

Aorimn commented Apr 3, 2016

I’m not sure about the version, but it shouldn’t be too old. Would it be possible to have your linux distribution (fedora, redhat, centos, etc.) in order to reproduce the problem?

tianlaizhiyin commented Apr 5, 2016

LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: RedHatEnterpriseServer
Description: Red Hat Enterprise Linux Server release 6.5 (Santiago)
Release: 6.5
Codename: Santiago

gfahb commented Apr 6, 2016

Hi Aorimn,
I have the same problem on ubuntu 14.04 TLS. Intel 64-Bit

alokjadhav commented Apr 10, 2016

facing the same problem here.

/apps/dislocker$ make
Linking C shared library libdislocker.so
/usr/bin/ld: /usr/local/lib/libmbedcrypto.a(aes.c.o): relocation R_X86_64_32S against `.bss’ can not be used when making a shared object; recompile with -fPIC
/usr/local/lib/libmbedcrypto.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
make[2]: *** [src/libdislocker.so.0.6.1] Error 1
make[1]: *** [src/CMakeFiles/dislocker.dir/all] Error 2
make: *** [all] Error 2

ubuntu@ubuntu: /apps/dislocker$ cc —version
cc (Ubuntu 4.8.4-2ubuntu1 14.04.1) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

ubuntu@ubuntu: /apps/dislocker$ uname -a
Linux ubuntu 4.2.0-27-generic #32 14.04.1-Ubuntu SMP Fri Jan 22 15:32:26 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Any update on this error?

Aorimn commented Apr 10, 2016

Hi,
I can’t seem to be able to reproduce the problem on Ubuntu 14.04 x64 on a fresh install:
http://pastie.org/10792802
Can someone with the problem on Ubuntu paste me something with the same commands as in this paste, replacing the make command with make VERBOSE=1 , please?

I’ll test on CentOS 6.5 when I have more time.

Источник

recompile with -fPIC #41

Comments

rytis-paskauskas commented Jan 18, 2019

$ make
.
[ 15%] Linking CXX executable pdfalto
/usr/bin/ld: libs/image/png/linux/libpng.a(png.c.o): relocation R_X86_64_32 against `.rodata’ can not be used when making a PIE object; recompile with -fPIC
.

$ cc -v
Using built-in specs.
COLLECT_GCC=cc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/8.2.1/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure —prefix=/usr —libdir=/usr/lib —libexecdir=/usr/lib —mandir=/usr/share/man —infodir=/usr/share/info —with-bugurl=https://bugs.archlinux.org/ —enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ —enable-shared —enable-threads=posix —enable-libmpx —with-system-zlib —with-isl —enable-__cxa_atexit —disable-libunwind-exceptions —enable-clocale=gnu —disable-libstdcxx-pch —disable-libssp —enable-gnu-unique-object —enable-linker-build-id —enable-lto —enable-plugin —enable-install-libiberty —with-linker-hash-style=gnu —enable-gnu-indirect-function —enable-multilib —disable-werror —enable-checking=release —enable-default-pie —enable-default-ssp —enable-cet=auto
Thread model: posix
gcc version 8.2.1 20181127 (GCC)

Читайте также:  Не удается настроить обновления windows как отменить

Any ideas?
Thanks,
Rytis

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

Aazhar commented Jan 18, 2019

Thank you for this feedback.
Could send the output of this command :

Aazhar commented Jan 18, 2019

you need to generate build file using the flag PIC as showed in the error.
So you need to run cmake this way :

rytis-paskauskas commented Jan 20, 2019

$ uname -i
unknown
$ uname -a
Linux . 4.19.13-1-lts #1 SMP Sun Dec 30 07:38:47 CET 2018 x86_64 GNU/Linux

Aazhar commented Jan 20, 2019

Thanks for the information,
I can’t reproduce this error in my environment, but I think you need to regenerate the libpng.a.
To do so you to go under libs/image/png/src and run :

cmake «-DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=true» ./; make

This will generate a libpng.a file that you need to copy under libs/image/png/linux , since I understand you are using linux.

Please keep me informed.

Aazhar commented Jan 22, 2019

Could you update your repository and re make it.

Источник

cmake, -fPIC

Есть проет на cmake, при сборке cmake добавляет опцию -fPIC. Что эта за вещь, откуда она берется и как ее проконтролировать? Типа cmake находит в коде asm для PIC контроллеров что ли?

> Типа cmake находит в коде asm для PIC контроллеров что ли

Гы-гы, упал под стол 🙂

=) ну скажите пазязя

требуется для shared библиотек, особенно на x86_64
все правильно добавляет, читайте man gcc

Как контролировать — хз.

Дело в том что с этой опцией не собирается код, ругаясь на ассемблерные вставки

Что видимо вполне логично, ибо уже не PIC

платформа 32 бита?

-fno-pic можно в CFLAGS и CXXFLAGS добавить или -mauto-pic

вообще ассемблерные вставки таких проблем вызывать не должны, пишите багрепорт авторам кода

вообще ассемблерные вставки таких проблем вызывать не должны, пишите багрепорт авторам кода

Ох уж эти халявщики. Никто вам ничего не должен.

так я правильно понимаю, что на платформе поддерживающей PIC библиотека насильно скомпилированная с -fno-pic может грохнуться?

>требуется для shared библиотек, особенно на x86_64

А не x86? На x86_64 код всегда position independent

в целом -fPIC должен автоматически использоваться GCC для x86_64, но иногда он этого не делает, пример:

evy ^_^ sylvia /tmp/zlib-1.2.5 >export CC=gcc
evy ^_^ sylvia /tmp/zlib-1.2.5 >export CFLAGS=-O2
evy ^_^ sylvia /tmp/zlib-1.2.5 >./configure —enable-shared
.
gcc -O2 -fPIC -D_LARGEFILE64_SOURCE=1 -DPIC -c -o objs/zutil.o zutil.c
gcc -shared -Wl,-soname,libz.so.1,—version-script,zlib.map -O2 -fPIC -D_LARGEFILE64_SOURCE=1 -o libz.so.1.2.5 adler32.lo compress.lo crc32.lo deflate.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo uncompr.lo zutil.lo -lc -L. libz.a

fPIC DPIC были подставлены configure, а теперь отдадим флаги на суд gcc, убираю -fPIC из Makefile

ld: adler32.lo: relocation R_X86_64_32 against `.text’ can not be used when making a shared object; recompile with -fPIC
adler32.lo: could not read symbols: Bad value
collect2: ld returned 1 exit status

в целом -fPIC должен автоматически использоваться GCC для x86_64, но иногда он этого не делает, пример:

ld: adler32.lo: relocation R_X86_64_32 against `.text’ can not be used when making a shared object; recompile with -fPIC

Теперь осталось понять, почему использовать 32-битные иммедиэйты в библиотеке для 64-битной системы нельзя (вернее, не всегда возможно, и gcc об этом ничего знать не может и не должен), а для статически определимого бинарника — можно. И даже нужно.

Читайте также:  Модальное окно windows forms

Источник

Please consider to compile static libraries with -fPIC on Linux #1257

Comments

realead commented Jul 28, 2017

Static libraries (2.4.2) cannot be used for linking of a shared library on x86-64 Linux, the linker returns the following error:

relocation R_X86_64_32S against `.rodata’ can not be used when making a shared object; recompile with -fPIC SFML/lib/libsfml-system-s.a: error adding symbols: Bad value

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

eXpl0it3r commented Aug 1, 2017 •

Do you mean we should add this to CMake? Or do you just mean for the builds on the website? Or the builds that come with your package manager?

Also, we have a forum for such kind of discussions. We try to reserve the issue tracker for confirmed issues and feature.

realead commented Aug 2, 2017

I encountered this problems with static libraries downloaded from the homepage as I tried to use them for linking of a shared library. But I think if you are going change that, it only makes sense if you change it everywhere.

Here is a small reproducer, I hope it explains what I mean:

/usr/bin/ld: SFML-2.4.2/lib/libsfml-system-s.a(Err.cpp.o): relocation R_X86_64_32S against `.rodata’ can not be used when making a shared object; recompile with -fPIC
SFML-2.4.2/lib/libsfml-system-s.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

I’m not sure this is a feature request and consider it to be a bug of the build-configuration: I think the option -fPIC should be used, so the built SFML-libraries can be used for building shared libraries out of the box. But it is also possible, that I’m wrong — I don’t have much experience with this kind of things.

MarioLiebisch commented Aug 2, 2017

Never noticed this not set. Can’t test it right now, but does it compile if you omit -fPIC for our own code? Besides that I’d say it should be added by default. Can’t think of any reason not to use it right now.

jcowgill commented Aug 2, 2017

Traditionally, static libraries are compiled without -fPIC on Linux because it usually doesn’t have much use and on some architectures there is a small performance penalty for using it. You only need it if you’re compiling a shared library using it, whereas I expect most people want to compile their entire executable statically (which does not need the flag).

realead commented Aug 2, 2017

@MarioLiebisch To my knowledge, -fPIC is obligatory for shared libraries on Linux x86-64. So if I omit -fPIC for the cpp, the linker will complain already about the first object-file.

eXpl0it3r commented Aug 2, 2017

As pointed out by @jcowgill, static libraries on Linux are commonly compiled without -fPIC , as such SFML will follow this semi-standard.

Additionally the Linux binaries provided as download on the website are not really the recommended way to use SFML under Linux. Either use the SFML package provided by your package manager or if you need some special version or changes (like having the SFML libraries built with -fPIC ), build SFML from source yourself.

I’m going to close this issue. If you think this is too important to not be followed up further, please make a case for it on the SFML forum.

Источник

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