使用 Clang 和 LLVM 组装从 C++ 文件编译的 .s 文件时出现“行尾垃圾”,但适用于 C 文件

问题描述 投票:0回答:1

我正在学习如何使用 LLVM 工具链。我有一个

.cpp
文件,我正在尝试将其编译为 LLVM 位码文件,将 LLVM 字节码文件编译为汇编文件,然后将汇编文件汇编为程序。

这是

.cpp
文件,

#include <iostream>

int main() {
    std::cout << "Hello, world!\n";
}

这是我在命令行中输入的内容(取自LLVM 文档),

# Compile the C file into an LLVM bitcode file
clang -O3 -emit-llvm hello.cpp -c -o hello.bc

# Compile the program to native assembly using the LLC code generator
llc hello.bc -o hello.s

# Assemble the native assembly language file into a program
gcc hello.s -o hello.native

但是,在将本机汇编语言文件汇编成程序的最后一步时,我遇到了这个错误:

hello.s: Assembler messages:
hello.s:72: Error: junk at end of line, first unrecognized character is `,'

这是

hello.s
文件的一部分,

.L.str:                                 # @.str
    .asciz  "Hello world!\n"

    .section    .ctors,"dw"
    .p2align    3
    .quad   _GLOBAL__sub_I_hello.cpp
    .section    .rdata$.refptr._ZSt4cout,"dr",discard,.refptr._ZSt4cout
    .p2align    3
    .globl  .refptr._ZSt4cout

第72行对应这一行,

.section    .rdata$.refptr._ZSt4cout,"dr",discard,.refptr._ZSt4cout

如果我按照上述相同步骤操作,但使用

.c
文件,则最后一步有效并且能够生成
hello.native
文件。

我想知道为什么上述步骤不适用于

.cpp
文件,以及我必须对
.cpp
文件做哪些不同的事情?

windows assembly gcc clang llvm
1个回答
0
投票

对于 cpp 来说,这是一个非常小的变化。我在这里使用 clang-17,需要一些标志才能完成这项工作 - 请参阅我明确使用了 cpp 对应项 -

clang++
g++

$ clang++-17 -c hello.cpp -fPIE -emit-llvm -o hello.bc
$ llc-17 --relocation-model=pic hello.bc -o hello.s
$ g++ hello.s -o hello.native
$ ./hello.native
Hello, world!

编译器版本是

$ g++ --version
g++ (Ubuntu 13.2.0-4ubuntu3) 13.2.0
Copyright (C) 2023 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.
$ clang++-17 --version
Ubuntu clang version 17.0.2 (1~exp1ubuntu2.1)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
© www.soinside.com 2019 - 2024. All rights reserved.