You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

gcc编译生成abc.o执行报错:Exec format error技术求助

Understanding GCC Compilation Stages & Your Exec 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:

  1. gcc abc.c -o abc.o
    This command runs both compilation AND linking in one step. Even though you named the output abc.o, this is actually a fully functional executable file. GCC doesn't care about the file extension here—it just follows your -o flag to name the output. That's why you can run it directly.

  2. gcc abc.c -c
    The -c flag 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 libc which provides printf)
    • 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). Adding chmod +x fixes the permission issue, but...
  • ./abc.o: cannot execute binary file: Exec format error: The file abc.o output confirms this—ELF 64-bit LSB relocatable means 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:

  1. Compile to object file:
    gcc abc.c -c -o abc.o
    
  2. Link the object file into an executable:
    gcc abc.o -o abc
    
  3. 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 -c will show ELF 64-bit LSB relocatable

内容的提问来源于stack exchange,提问作者guapi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:23:13