Language/C
[따배씨] 12.8 정적 변수의 외부 연결
migrationArc
2021. 6. 14. 21:39
따배씨 - 따라하며 배우는 C언어
12강 Storage Classes, Linkage and Memory Management
12.8 정적 변수의 외부 연결 external linkage
- 여러 파일로 작성된 코드를 각각의 파일을 complier 가 따로따로 complie 하여 obj 파일을 만들고, 실행파일을 만들기 전에 linker 가 연결
- external linkage 를 갖는 변수들도 연결
// main.c
#include <stdio.h>
#include "second.c"
/*
Static variable with external linkage
- File scope, external linkage, static storage duration
- External storage class
- External variables
*/
int g_int = 7; // static variable 은 complier 가 0으로 알아서 초기화 해줌
double g_arr[1000] = {0, 0, }; // 하지만 초기화 하는것이 권장
/*
Initializing External Variables
*/
int x = 5; // ok, constant expression
int y = 1 + 2; // ok, constant expression
size_t z = sizeof(int); // ok, sizeof is a consant expression
//int x2 = 2 * x; // not ok, x is a variable // 변수가 들어간 값으로 초기화 안됨
void func(){
printf("g_int in func() %d %p\n", g_int, &g_int);
g_int += 10;
}
int main(){
/*
defining declaration vs referencing declaration
*/
//extern double g_arr[];
//extern int g_int; // extern 을 사용해 file scope의 변수가 scope 에서 선언되는 것을 방지 가능
//int g_int = 123; // hiding global g_int, func() 에서는 global g_int 가 사용됨
printf("g_int in main() %d %p\n", g_int, &g_int);
g_int += 1;
func();
fun_sec();
return 0;
}
//////////////////////////
//second.c
//
// second.c
// studyC
//
// Created by 이주호 on 2021/04/05.
//
#include <stdio.h>
//extern int g_int = 777; // file scope 에서는 초기화 가능, 하지만 각각의 파일에서 모두 초기화 하였을 때 Linkin Error
void temp(){
//extern int g_int = 777; // extern 변수는 block scope 초기화 불가
extern int g_int;
g_int += 1000;
}
void fun_sec(){
temp();
extern int g_int;
g_int += 7;
printf("g_int in fun_sec() %d %p\n", g_int, &g_int);
}
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com