본문 바로가기
개발/C, C++

C/C++ 컴파일 및 실행 (여러 파일, 헤더파일 포함)

by amkorousagi 2023. 2. 17.

설명


C/C++에서 소스코드를 컴파일(compile)하고 실행(execute)하는 방법에 대하여 설명합니다.

특히 여러 파일과 헤더 파일이 있는 경우에 대하여 다룹니다.

방법


우선, 현재 디렉토리에 다음과 같은 파일들을 만듭니다,

 

main.c

#include <stdio.h>
#include "foo.h"

int main(void){
    int y =  foo(100);
    printf("%d",y);
    return 0;
}

 

foo.c

#include "foo.h"

int foo(int x){
    return x + 5;
}

 

foo.h

int foo(int x);

 

 

그리고 컴파일 후 실행 합니다.

gcc main.c foo.c -o testc
testc

 

.h로 끝나는 헤더파일의 경우 같은 디렉터리 내에 존재해야 합니다.

 

없다면

main.c:1:10: fatal error: foo.h: No such file or directory 1 | #include "foo.h" | ^~~~~~~ compilation terminated. foo.c:1:10: fatal error: foo.h: No such file or directory 1 | #include "foo.h" | ^~~~~~~ compilation terminated.

과 같은 오류가 나옵니다.

 

또 #include "foo.h"를 모두 제거하거나 foo.h을 빈 파일로 만들면

main.c: In function 'main': main.c:4:13: warning: implicit declaration of function 'foo' [-Wimplicit-function-declaration] 4 | int y = foo(100); |

과 같은 오류가 나옵니다.

 

C/C++의 경우 main 함수가 항상 entry point 이기 때문에 entry에 관련한 설정이 필요없습니다.

 

참조


 

 

Creating your own header file in C

Can anyone explain how to create a header file in C with a simple example from beginning to end.

stackoverflow.com

 

 

댓글