gcc静态链接库过程中,关于强类型和弱类型的知识

本文探讨了在GCC静态链接过程中遇到的同名变量或方法的处理方式,解释了强弱符号的概念及其规则。链接器在解析时遵循只允许一个强符号存在、强符号优先于弱符号、多个弱符号则选取一个的原则。通过实例分析,展示了静态库链接时,链接器可能仅链接首个符号,而动态库则按照链接顺序处理。最后,指出强弱符号在静态库中的冲突情况,强调理解强弱符号对于避免链接错误的重要性。
摘要由CSDN通过智能技术生成

问题:在gcc静态链接的过程中,如果多个模块有同名变量,链接顺序如何?是否会有冲突?

1、我们先测试下面这段代码,发现同名变量或者方法,不是一定会发生冲突的:

//common.h
#ifndef COMMON_H
#define COMMON_H
#include<iostream>
using namespace std;
#ifndef LABEL
#define LABEL "common"
#endif
class Common{
public:
  static void f() {
    cout << "Common::f "
   << LABEL << endl;
  }
};
void __attribute__((weak)) disp() {}
#endif // COMMON_H
//a.h
#ifndef A_H
#define A_H
class A
{
public:
    void f();
};
#endif // A_H
//a.cc
#define LABEL "a"
#include "a.h"
#include "common.h"
#include <iostream>
#include <stdio.h>
using namespace std;
void A::f() {
  cout << "[A::f]" << endl;
  typedef void (*P)();
  P p = Common::f;
  printf("%p\n", p);
  //打印函数指针值
  p();
}
//b.h
#ifndef B_H
#define B_H
class B
{
public:
    void f();
};
#endif // B_H
//b.cc
#define LABEL "b"
#include "b.h"
#include "common.h"
#include <iostream>
#include <stdio.h>
using namespace std;
void B::f() {
  cout << "[B::f]" << endl;
  typedef void (*P)();
  P p = Common::f;
  printf("%p\n", p);
  //打印函数指针值
  p();
}
//main.cc
#define LABEL "main"
#include "a.h"
#include "b.h"
#include "common.h"
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
  A a;
  a.f();
  B b;
  b.f();
  cout << "[main]" << endl;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值