【问题标题】:Clang does not accept -shared -fPIC -pie compiler flags simultaneouslyClang 不同时接受 -shared -fPIC -pie 编译器标志
【发布时间】:2020-05-05 17:02:22
【问题描述】:

由以下代码给出:

#include <stdio.h>

void output()
{
  printf("hello \n");
}

int main()
{
  output();
  return 0;
}

当上述代码通过以下命令编译时:

gcc hello.c -shared -fPIC -pie -o libhello.so -Wl,-E

生成的libhello.so不仅是共享库,还是可执行文件。但是,当将 gcc 更改为 clang 时,如下所示

clang-10 hello.c -shared -fPIC -pie -o libhello.so -Wl,-E

编译给出以下警告:

clang: warning: argument unused during compilation: '-pie' [-Wunused-command-line-argument]

在执行clang-10编译的libhello.so时,也崩溃了。

问题: 1、gcc可以使用clang compile runnable shared lib吗?

注意:这个问题只是出于我自己的好奇心而提出的,我没有遇到任何实际问题。

【问题讨论】:

  • 看起来clang不像GCC那样喜欢生成可执行的共享库,因此它没有添加标准的libc函数来启动程序,也没有添加所需的PT_INTERP ELF程序头,在启动时导致段错误,因为内核认为程序必须在没有解释器的情况下启动。您可以尝试编写自己的 _start() 函数,看看会发生什么。
  • @MarcoBonelli,非常感谢您的帮助。除了_start(),我们还必须强制clang-10 在共享对象程序头中生成INTERP 段。问题中也给出了该示例的详细信息。
  • @MikeKinghan。感谢您的提示,我按照建议发布了一个新答案。

标签: c gcc clang


【解决方案1】:

clang-10 发出警告,clang-10 不会像 GCC 编译器那样生成以下内容:

  1. 共享库的程序头中的INTERP段
  2. _start() 函数

两者都可以手动如下

#include <stdio.h>

const char interp_section[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";

void output()
{
  printf("hello \n");
}

int main()
{
  output();
  return 0;
}

void _start()
{
  printf("hello.c : %s\n", __FUNCTION__);
  exit(0);
}

但是,最好使用-Wl,-e,YourEntryFunction 标志来创建可运行的共享对象,而不是上述问题中提出的方法。

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多