学习日志
为什么 C 比汇编更容易跨平台?
A question suddenly came to mind today: why does C have relatively good portability, while assembly is usually difficult to port across different architectures?
The key is that they express program behavior at different levels.
Assembly code already targets a specific ISA. When writing assembly, I need to use the instructions, registers, and operations that architecture provides. For example, a piece of RISC-V assembly cannot be executed directly on an ARM CPU. Changing architectures usually means reworking the implementation.
C provides a higher level of expression. When I write c = a + b, I am expressing “add a and b, then assign the result to c,” without specifying which registers or machine instructions must be used.
Compilers targeting different platforms can translate the same C source code into machine code suitable for each platform. The programmer keeps a relatively general description of the behavior and leaves the choice of specific instructions to the compiler. This is an important reason why C is easier to use across platforms.
What I understand as portability today is mainly source-code portability: when the language and execution-environment requirements are met, the same source code can be recompiled for different platforms, rather than the same executable running everywhere.
C leaves room for the compiler to choose an implementation for the target platform; assembly has already written more of those specific machine choices into the code.
I have been reading The C Programming Language. With my teacher’s guidance today, I began to reconsider how I approach this book: as more than a reference manual or a guide to quickly learning C syntax.
My teacher suggested a method: “pruning (planting a stake)”—choosing a single target to explore in depth.
At this stage, I do not need to finish learning all the fundamentals before tackling real problems. I can start exploring a specific problem and fill in the relevant foundations as needed.
When new questions arise during that exploration, I can write them down without immediately following every branch. First, I should clarify exactly what I want to understand this time and make that the focus of my exploration.
今天突然脑海里冒出了一个问题:为什么 C 语言具有较好的可移植性,而汇编语言通常难以跨不同架构移植?
关键在于,它们表达程序行为时,所处的层次不同。
汇编代码已经面向具体的 ISA。 写汇编时,我需要使用这套架构提供的指令、寄存器和操作方式。例如,一段 RISC-V 汇编不能直接拿到 ARM CPU 上执行;换了架构,通常就需要重新安排实现方式。
C 则提供了更高一层的表达。我写下 c = a + b,表达的是“把 a 和 b 相加,再把结果赋给 c”,并没有指定一定使用哪几个寄存器、哪一种机器指令。
面向不同目标平台的编译器,可以把同一份 C 源码翻译成各自适用的机器代码。 程序员保留较通用的行为描述,把具体指令的选择交给编译器。这是 C 更容易跨平台的重要原因。
我今天理解的可移植性,主要是源码层面的可移植性:在满足语言和运行环境要求的条件下,同一份源码可以为不同平台重新编译,而不是同一个可执行文件到处运行。
C 保留了让编译器为目标平台选择实现方式的空间;汇编则已经把更多具体的机器选择写进了代码。
最近正在读《C 程序设计语言》。今天在老师的指点下,我开始调整看待这本书的方式:不再只把它当作一本工具书,或是快速掌握 C 语言语法的指南。
老师提到一个方法:“剪枝(打桩)”,锁定唯一的深挖目标。
对现阶段的我来说,不必等到把所有基础知识学完,才开始接触真实问题。我可以先围绕一个具体问题展开探索,再根据需要补齐相关的基础知识。
探索中不断冒出的新问题,可以先记下来,不急着沿每条分支追下去。先明确这次究竟要弄懂什么,把它作为当前的深挖目标。