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

未重定义时__attribute__((weak))弱函数未被调用问题排查

问题:弱函数调用后程序窗口闪关无输出?

代码文件

main.c

#include <stdio.h>
#include <stdlib.h>
#include"Test.h"

int main()
{
   test_function();
   return 0;
}

Test.c

#include<stdio.h>
#include<stdlib.h>
#include"Test.h"

void __attribute__((weak)) test_function()     
{
    printf("Test_fuction \n");
    getchar();
}

Test.h

#ifndef TEST_H
#define TEST_H
#include<stdio.h>

void __attribute__((weak)) test_function();

#endif  // TEST_H

编译流程

gcc -c main.c -o main.o
gcc -c Test.c -o Test.o
gcc main.o Test.o -o main

问题描述

按照弱函数特性,未重定义时应调用该弱函数,预期运行程序会打印Test_function,但实际运行main.exe时窗口闪关,无任何输出。

问题分析与解决

你的弱函数使用逻辑是正确的,问题出在以下两点:

  1. 字符串拼写错误:Test.c中printf的字符串是Test_fuction(少了字母n),即使正常显示,输出内容也和预期不符,需修正为Test_function。

  2. Windows窗口闪关问题:
    在Windows环境下双击运行exe时,程序执行完成会立即关闭控制台窗口,导致你来不及查看输出。虽然代码里有getchar(),但printf输出的换行符可能残留在输入缓冲区中,getchar()会直接读取该换行符,程序随即退出,不会等待用户输入。

    解决方法二选一:

    • 在test_function中先清空输入缓冲区,再调用getchar():
      void __attribute__((weak)) test_function()     
      {
          printf("Test_function \n");
          // 清空缓冲区残留的换行符
          while (getchar() != '\n');
          getchar();
      }
      
    • 在main函数末尾添加system("pause");(main.c已包含<stdlib.h>,可直接使用):
      int main()
      {
         test_function();
         system("pause");
         return 0;
      }
      

内容的提问来源于stack exchange,提问作者Mr. Nothing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:55:07