gcc编译生成abc.o执行报错:Exec format error技术求助
Hey there! Let's clear up this confusion—it's a super common pitfall when you're getting familiar with GCC. Let's break down exactly what's happening with your commands and why you're seeing those errors.
First: The Difference Between Your Two GCC Commands
You're using two similar-looking commands, but they do completely different things:
gcc abc.c -o abc.o
This command runs both compilation AND linking in one step. Even though you named the outputabc.o, this is actually a fully functional executable file. GCC doesn't care about the file extension here—it just follows your-oflag to name the output. That's why you can run it directly.gcc abc.c -c
The-cflag tells GCC to only run the compilation stage (turning your C code into assembly, then into machine code) but skip linking. The result is a relocatable object file—this is an intermediate file that contains your compiled code, but it's missing all the stuff needed to run as a standalone program:- It doesn't have the startup code that tells the OS how to launch your program
- It hasn't been linked to system libraries (like
libcwhich providesprintf) - It's not formatted as an executable that the kernel can load
Why You're Seeing Those Errors
Let's walk through each error:
bash: ./abc.o: Permission denied: By default, GCC doesn't set executable permissions on object files (since they're not meant to be executed). Addingchmod +xfixes the permission issue, but..../abc.o: cannot execute binary file: Exec format error: Thefile abc.ooutput confirms this—ELF 64-bit LSB relocatablemeans this is a relocatable object file, not an executable. Your OS knows it can't run this type of file, hence the error. Your architecture (x86_64) matches, but the file type is wrong.
The Correct Workflow
If you want to split compilation and linking (useful for larger projects), here's how to do it properly:
- Compile to object file:
gcc abc.c -c -o abc.o - Link the object file into an executable:
gcc abc.o -o abc - Now run the executable:
./abc
If you just want a quick executable without splitting stages, skip the -c flag and use a clearer name (no .o suffix to avoid confusion):
gcc abc.c -o abc ./abc
To confirm the difference, run file on both outputs:
- The executable from the first command will show
ELF 64-bit LSB executable - The object file from
-cwill showELF 64-bit LSB relocatable
内容的提问来源于stack exchange,提问作者guapi

