[英]Why do I have to recompile my C program when I move it from OSX to a Ubuntu machine?
I built a bunch of simple C programs for school on my Mac (OSX). 我在Mac(OSX)上为学校构建了一堆简单的C程序。 I had compiled all of the programs and tested them all on my Mac with a Makefile. 我编译了所有程序,并在我的Mac上用Makefile对它们进行了全部测试。 Everything worked well. 一切都运作良好。
To prep for an assignment tomorrow, I decided to transfer all of these files (compiled and source code) via SSH to the class network (OS is Ubuntu). 为了明天准备作业,我决定通过SSH将所有这些文件(编译和源代码)传输到类网络(操作系统是Ubuntu)。 I wanted to make sure everything worked as expected there. 我想确保一切按预期工作。
Once I transferred everything, when I tried to use the Emacs shell to run the compiled programs, I got a Cannot execute binary file
error. 一旦我转移了所有内容,当我尝试使用Emacs shell运行已编译的程序时,我得到了一个Cannot execute binary file
错误。 Then, once I recompiled via my Makefile over SSH on the Ubuntu machine, it worked fine. 然后,一旦我通过Ubuntu机器上的SSH通过我的Makefile重新编译,它运行正常。 But why not before? 但为什么不呢?
I know this is obvious to some of you, but I don't know why a compiled C program will run fine on my machine, but then have to be recompiled on a different machine even with the operating systems being different? 我知道这对你们中的一些人来说是显而易见的,但是我不知道为什么编译的C程序在我的机器上运行正常,但是即使操作系统不同,也必须在不同的机器上重新编译?
Here is an example of my Makefile compile commands: 以下是我的Makefile编译命令的示例:
example: example.c
gcc -Wall -pedantic -ansi example.c -o example
I'm pretty new to C (obviously). 我很擅长C(显然)。 This question, Why does my program run on Ubuntu gcc but not OSX gcc? 这个问题, 为什么我的程序在Ubuntu gcc上运行但不在OSX gcc上运行? , seems similar but I don't understand the answer. ,似乎相似,但我不明白答案。
Like other have mentioned the C code might be compatible but Linux and OSX use different binary formats which are not compatible. 像其他提到的那样,C代码可能兼容,但Linux和OSX使用不兼容的不同二进制格式。 Thus you will need to recompile to make your code run on the other platform. 因此,您需要重新编译才能使代码在其他平台上运行。
Linux uses a binary format called ELF Linux使用称为ELF的二进制格式
OSX uses a binary format called Mach-O OSX使用称为Mach-O的二进制格式
See Is a Linux executable “compatible” with OS X? 请参阅Linux X可执行文件与OS X“兼容”吗? for a more in depth explanation. 进一步深入解释。
so to add to Marius's very good explanation: 所以加上马吕斯的非常好的解释:
they actually use the same x86-64 (amd64) calling convention (ABI) so they are compatible on another level, deeper than just C... but they are packaged in different object file formats (as described by Marius). 它们实际上使用相同的x86-64(amd64)调用约定(ABI),因此它们在另一个级别上兼容,比C语言更深......但它们以不同的目标文件格式打包(如Marius所述)。
The other major difference is the linker... so while they both implement std C functions, they are in different libraries so if they are dynamically linked the symbols are in the wrong place. 另一个主要区别是链接器......所以虽然它们都实现了std C函数,但它们位于不同的库中,因此如果它们是动态链接的,则符号位于错误的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.