따배씨++ (4-2.2 external linkage)

김동우·2021년 4월 17일
0

안녕하십니까. 김동우입니다.

이전 노트의 후속편이며, 외부파일 링크와 관련된 내용을 적고자 합니다.

그럼 코드를 보시겠습니다.

  1. MyConstants.cpp
namespace Constants
{
    extern const long double permittivity(8.8541878176e-12);
    // 초기화하여 메모리를 할당하고, 다른 파일에서도 해당 값과 주소만을 이용할 수 있게 한다.
}
  1. MyConstants.h
#pragma once

namespace Constants
{
    const float gravity(9.8f);
    const double pi(3.141592); // namespace로 묶는게 extern보다 덜 번거롭다.
    // 헤더에서의 초기화는 사용처마다 메모리를 재할당한다.

    extern const long double permittivity;
    // MyConstants.cpp 에서 해당 변수의 주소를 전송받는다. 이때, 메모리 주소는 cpp에서 할당한다.
    // 즉, 이러한 경우 어디서 불러오든 동일한 메모리주소를 할당받게 되고,
    // 해당 선언을 활용하면 불필요한 메모리 낭비를 줄일 수 있다.
    // 자세한 실행결과는 main.cpp에서 확인. 
}
  1. test.cpp
#include <iostream>
#include "MyConstants.h"

void doSomething()
{
    using namespace std;
    cout << "Text from test.cpp" << endl;
    cout << "Gravity and Pi in test.cpp" << '\n'
    << Constants::gravity << " " << Constants::pi << endl;
    cout << "The memory of Gravity and Pi in test.cpp" << '\n'
    << &Constants::gravity << " " << &Constants::pi << endl;
    cout << "Permittivity in test.cpp" << '\n' 
    << &Constants::permittivity << " " << Constants::permittivity << endl;
}

extern int test_a(888);
  1. main.cpp
#include <iostream>
#include "MyConstants.h"
using namespace std;

// forward declaration
extern void doSomething(); // == void doSomething();
extern int test_a; // == int test_a;

int main()
{   
    doSomething(); // output : Test from test.cpp
    cout << test_a << endl;
    // (output)
    // 888
    // Gravity and Pi in test.cpp
    // 9.8 3.14159
    // The memory of Gravity and Pi in test.cpp
    // 0x104a33e88 0x104a33e90
    // Permittivity in test.cpp
    // 0x104dcfd70 8.85419e-12

    cout << Constants::gravity << " " << Constants::pi << endl;
    // output : 9.8 3.14159
    cout << &Constants::gravity << " " << &Constants::pi << endl;
    // output : 0x100927e78 0x100927e80
    // test.cpp에서 불러온 Constants들과 다른 주소값을 가진다.
    // 이는 메모리 낭비를 야기하기도 한다.
    cout << &Constants::permittivity << " " << Constants::permittivity << endl;
    // output : 0x104dcfd70 8.85419e-12
    // test.cpp 내의 permittivity와 동일한 주소와 값을 가져온다.
    // h file 내에서의 선언은 초기화가 없는 형태이며,
    // MyConstants.cpp 내에서 초기화를 진행하여 외부로 값을 연결한다.
    // obj -> link 과정을 이용하는 방식이 된다.
    // 이 모든 연결을 external linkage라 하며,
    // static 은 internal linkage의 예가 되어 범위가 다른 개념이 된다.
    // 또한 const 값은 단 한 번의 초기화를 요구하고, 
    // 이는 무조건 어느 한 곳에서는 초기화를 진행한다는 말이 된다.

    return 0;
}

이번 강의는 꽤나 길었습니다.

그럼 이만 이번 글을 마치도록 하겠습니다. 감사합니다.

0개의 댓글

관련 채용 정보