C언어/기본 개념

분할 컴파일

D.Kyeom 2023. 2. 23. 15:59
728x90

분할 컴파일 방법

여러개 파일로 작성 후 링크 단계에서 합친다.

특징

  • 각 파일에 컴파일에 필요한 선언을 포함해야한다.
  • 이미 만들어진 소스 파일이나 개체 파일도 프로젝트에 포함 할 수 있다.

다른 파일의 전역 변수를 사용 할 때: extren / 다른 파일에서 전역 변수를 공유하지 못하게 만들 때: static

main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int input_data(void);
double average(void);
void print_data(double);
int cnt = 0;
static int tot = 0;
int main(void
{
    double avg;
 
    tot = input_data(); //sub.c 파일에서 return한 tot 값을 저장
    avg = average();
    print_data(avg);
 
    return 0;
}
void print_data(double avg)
{
    printf("입력한 양수의 개수 : %d\n", cnt);
    printf("전체합과 평균 : %d, %.1lf\n", tot, avg);
 
}
cs

 

sub.c

2행 cnt 변수는 main.c파일에 있는 cnt변수

3행 tot 변수는 sub.c 파일에서 새로 만든 변수(main.c에서 stactic으로 사용을 막았기 때문) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
extern int cnt;
int tot= 0;
int input_data(void)
{
    int pos;
    while (1)
    {
        printf("양수 입력 : ");
        scanf("%d"&pos);
        if (pos < 0)break;
        cnt++;
        tot += pos;
    }
    return tot;
}
 
cs

 

average.c

1행 cnt는 main.c

2행 tot는 sub.c 

1
2
3
4
5
6
7
extern int cnt;
extern int tot;
 
double average(int a, int b)
{
    return tot/(double)cnt;
}
cs

헤더 파일의 필요성

  • 각 파일에 공통으로 필요한 코드를 모아 만든다. (함수 선언, 구조체형 선언, extern 선언)
    • 수정을 해도 헤더 파일로 사용하면 선언한 부분마다 가서 다시 선언 할 필요가 없다.
  • 헤더 파일의 수정내용을 빠르고 정확하게 반영
  • 다른 프로그램 헤더 파일 내용 재할용

 

728x90