C++ 内部链接 vs 外部链接

2021-06-15  本文已影响0人  _大橙子_

ref: https://www.geeksforgeeks.org/internal-linkage-external-linkage-c/

导读

生命周期(scope)和链接方式(linkage)很容易混淆,本文主要介绍生命周期和链接方式在C++中如何起作用的。

定义

举例

内部链接

代码

// Animal.h
#ifndef ANIMAL_H_
#define ANIMAL_H_

void call_me(void);

static int animals = 8;
const int i = 5;

#endif
//Animal.cpp

#include <stdio.h>
#include "Animal.h"
void call_me(void)
{
    printf("const int i=%d, static int animals = %d\n", i, animals);
    printf("in Animal.cpp &i = %p,&animals = %p\n", &i, &animals);
}
// Feed.cpp
#include <stdio.h>
#include "Animal.h"
  
int main()
{
    printf("before change aninals:");
    call_me();
    animals = 2;
    printf("after change aninals:");
    printf("animals = %d\n", animals);
    call_me();

    printf("in Feed.cpp &i = %p,&animals = %p\n", &i, &animals);
    return 0;
}

编译链接

% g++ Feed.cpp Animal.cpp -o Feed  

运行

% ./Feed
before change aninals:const int i=5, static int animals = 8
in Animal.cpp &i = 0x10081dfa8,&animals = 0x100822014
after change aninals:animals = 2
const int i=5, static int animals = 8
in Animal.cpp &i = 0x10081dfa8,&animals = 0x100822014
in Feed.cpp &i = 0x10081dfa4,&animals = 0x100822010

分析

在Animal.cpp和Feed.cpp中, 变量i和animals的地址是不同的,即每个文件都是不同的变量。

外部链接

代码

// Animal.h
#ifndef ANIMAL_H_
#define ANIMAL_H_

void call_me(void);
extern int animals ;
extern const int i;

#endif
// Animal.cpp
#include <stdio.h>
#include "Animal.h"
int animals = 8;
const int i = 5;
void call_me(void)
{
    printf("const int i=%d, static int animals = %d\n", i, animals);
    printf("in Animal.cpp &i = %p,&animals = %p\n", &i, &animals);
}
// Feed.cpp
#include <stdio.h>
#include "Animal.h"
  
int main()
{
    printf("before change aninals:");
    call_me();
    animals = 2;
    printf("after change aninals:");
    printf("animals = %d\n", animals);
    call_me();

    printf("in Feed.cpp &i = %p,&animals = %p\n", &i, &animals);
    return 0;
}

编译链接

% g++ Feed.cpp Animal.cpp -o Feed  

运行

% ./Feed
before change aninals:const int i=5, static int animals = 8
in Animal.cpp &i = 0x100d14fb4,&animals = 0x100d19010
after change aninals:animals = 2
const int i=5, static int animals = 2
in Animal.cpp &i = 0x100d14fb4,&animals = 0x100d19010
in Feed.cpp &i = 0x100d14fb4,&animals = 0x100d19010

分析

在Animal.cpp和Feed.cpp中, 变量i和animals的地址是相同的,即所有的文件中该变量是共享的。

上一篇 下一篇

猜你喜欢

热点阅读