• 검색 결과가 없습니다.

C 언어 맛보기 #4 – 함수 2

N/A
N/A
Protected

Academic year: 2022

Share "C 언어 맛보기 #4 – 함수 2"

Copied!
33
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

Intelligence Networking and Computing Lab.

C 언어 맛보기 #4 – 함수 2

부산대학교 전기컴퓨터공학부 김종덕 ([email protected])

본 강의 자료는 문정욱 교수님의 강의 자료를 활용하여 작성하였습니다.

(2)

Intelligence Networking and Computing Lab.

강의의 목표

❖ C 언어의 전처리기를 이해한다.

▪ #include와 #define

❖ 함수의 정의(Definition)와 선언/원형(Declaration/Prototype)의 차이 를 이해한다.

▪ Interface와 Implementation을 구별할 수 있다.

▪ Modular Programming의 개념을 이해한다.

❖ C Standard Library의 의미를 이해한다

▪ C Standard Library 활용하기 위한 기본 방법을 이해한다.

❖ 사용자 Library를 활용하는 기본 방법을 이해한다.

2

(3)

Intelligence Networking and Computing Lab.

Preprocessor Directive

❖ 전처리기(preprocessor)

▪ 컴파일러가 프로그램을 번역하기 '전' 에 소스 프로그램을 '처리'하는 프로그램

❖ 전처리기 지시자(preprocessor directive)

▪ 전처리기에게 특정 작업을 지시하는 유사명령어

▪ 실제로 실행 시간에 수행되는 명령어가 아님

▪ #으로 시작함

❖ 중요한 전처리기 지시자

▪ #include: 다른 파일의 내용을 현재 파일에 포함시킴

▪ #define: 특정 단어를 다른 문자열로 바꿈

3

(4)

Intelligence Networking and Computing Lab.

#include

❖ 파일 포함 지시자

❖ 헤더파일(header file)

▪ 다른 파일에 포함시킬 목적으로 작성된 파일

▪ 인클루드 파일(include file)이라고도 함

4

(5)

Intelligence Networking and Computing Lab.

Header File 위치에 따른 차이

❖ <표준 헤더파일>

▪ 개발 환경이나 시스템에 의해 미리 설정된 경로에 존재

▪ 지정된 경로를 편집할 수도 있다  후반부에 예제 있음

❖ "일반 헤더파일"

▪ 소스파일과 같은 위치에서 찾을 수 있는 파일

5

(6)

Intelligence Networking and Computing Lab.

#define

❖ 다른 문자열로 대치될 단어(매크로; macro)를 정의함

▪ #define 관련 대표적 오류

6

#include <stdio.h>

#define MESSAGE "Hello World\n"

int main(void) {

printf(MESSAGE);

return 0;

}

#include <stdio.h>

int main(void) {

printf("Hello World\n");

return 0;

}

After

Preprocessing

#include <stdio.h>

#define MESSAGE "Hello World\n";

int main(void) {

printf(MESSAGE);

return 0;

}

#define Name Definition

#include <stdio.h>

int main(void) {

printf("Hello World\n";);

return 0;

}

After

Preprocessing

(7)

Intelligence Networking and Computing Lab.

Macro Function

❖ 함수 형태의 매크로

▪ 실제로 함수는 아니지만 인수를 받는 형태임

7

#define Name(x) Definition

#include <stdio.h>

#define SQUARE(a) a*a int main(void)

{

double x = 2.5;

printf("x^2 == %f\n", SQUARE(x));

return 0;

}

After Preprocessing

#include <stdio.h>

int main(void) {

double x = 2.5;

printf("x^2 == %f\n", x*x);

return 0;

}

(8)

Function Declaration/Prototype

❖ Prototype

▪ 함수의 정의(Definition)에서 Body 부분 을 제거하고 Interface만 있는 것을 함 수 선언(Declaration) 또는 함수 원형 (Prototype)이라고 함

▪ 함수를 호출하는 입장에서는 함수가 제 공하는 기능을 이해하고 있다면 굳이 함수 Body의 세부 내용을 알 필요는 없 음.

▪ Prototype을 이용하면 함수의 Body를 포함하는 함수 Definition을 다른 곳으 로 이동시킬 수 있음

❖ 우측 코드에서 Prototype이 없으면 어떤 문제가 발 생하는가?

Implicit Declaration vs. Explicit Declaration.

❖ C에서는 변수든 함수든

사용하기 전에 선언하는 것이 매우 바람직

8

function_Prototype:

ret_type funct_name(arguments);

#include <stdio.h>

#define MY_PI 3.14

// Function Prototype/Declarations double square(double a);

double circle(double r);

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

// Function Definition double square(double a) {

return a*a;

}

double circle(double r) {

return MY_PI*square(r);

}

(9)

Modular Programming

❖ Divide & Conquer

크고 복잡한 일을 덜 복잡한 일들로 나눠서 해결 하는 접근법

함수 분리, 소스 파일 분리, …

❖ 소스 파일의 분리

mymath.c라는 소스 파일을 프로젝트에 추가하고 main()외 추가 함수의 정의를 포함.

Build 후 Debug 폴더에 .o 파일을 확인하라.

9 main.c

#include <stdio.h>

// Function Prototype/Declaration double square(double a);

double circle(double r);

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

main.c

#define MY_PI 3.14 double square(double a) {

return a*a;

}

double circle(double r) {

return MY_PI*square(r);

}

mymath.c

main.o

mymath.o

compiling

compiling

prj.exe

linking

#include <stdio.h>

#define MY_PI 3.14

// Function Prototype/Declarations double square(double a);

double circle(double r);

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

// Function Definition double square(double a) {

return a*a;

}

double circle(double r) {

return MY_PI*square(r);

}

(10)

Intelligence Networking and Computing Lab.

Header 파일

❖ Header File :.h file; .c  source file

▪ 다른 파일에서 필요한 함수의 선언 등을 정리한 파일

❖ my_lib.h 라는 새로운 Header File을 추가하자.

▪ “#include” 다른 파일을 포함시킨다는 의미

▪ 생성된 헤더 파일에 square(), circle() 함수의 prototype을 작성.

• #ifndef 등은 자동 생성된 preprocessor directive

▪ main.c는 prototype 제거, 대신 #include “my_lib.h” 추가

10

#include <stdio.h>

#include "my_lib.h"

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

main.c

#include <stdio.h>

// Function Prototype/Declaration double square(double a);

double circle(double r);

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

main.c

(11)

Intelligence Networking and Computing Lab.

Interface vs. Implementation

❖ 함수(서비스)를 호출하는(이용하는) 입장에서는

함수(서비스)가 제공하는 기능과 호출하는 방법(Interface)을 안다면 함수(서비스)의 세부(구현) 내용을 알 필요가 없음  Black Box

▪ C/C++ 언어에서

Header File은 Interface의 역할을 Source File은 Implementation 의 역할을 한다.

11

Main Source 서비스 함수 이용자

서비스 Source File Implementation 서비스 Header File

Interface compiling

Object File

compiling Object

File Library

File or 서비스 소스 파일이

없어도 Compile에 문제가 없음 !!!

prj.exe 실행 파일을 생성하기

위해서는 객체 파일 또는 라이브러리 파일 필요

linking

(12)

Interface and Implementation

12

(13)

Intelligence Networking and Computing Lab.

Abstraction

❖ Abstraction is the process of generalization by reducing the

information content of a concept or an observable phenomenon, typically in order to retain only information which is relevant for a particular purpose

13

(14)

Intelligence Networking and Computing Lab.

Abstraction (in Computer Science)

❖ Hiding details of implementation in programs & data - Wikipedia

▪ The essence of abstractions is preserving information that is relevant in a given context, and forgetting information that is irrelevant in that context - John V. Gutta

❖Separation of Interface from Implementation

❖ Interface의 이해는 (Modular) Programming의 핵심

▪ Software 개발의 상당 부분은 Assembly (조립)이다.

▪ 타인이 작성한 모듈(부품)과 나의 모듈(부품)을 결합 시키는 작업

▪ 응용 프로그램을 짜기 쉽도록 운영체제 또는 플랫폼에서 제공하는 함수/서비스

 API : Application Programming Interface

▪ 현실 S/W 개발 시 이용할 수 있는 부품은 거의 100% 설명서가 영어임.

14

(15)

Intelligence Networking and Computing Lab.

C Standard Library

❖ 표준 입출력을 위해 사용한 printf()와 scanf() 역시 함수

❖ 이 함수의 Declaration은 어디에 있을까?  stdio.h

▪ stdio.h 파일은 어디에 존재할까?

❖ 이 함수의 Definition은 어디에 있을까?

▪ 이 함수들을 매번 소스 레벨에서 compile 시켜야 할까?

▪ 다른 프로그램 작성 시 이용할 수 있도록 미리 Compile 시켜 Object 파일으로 만들어 둔 파일  Library 파일

▪ MinGW Toolchain의 경우 Library 파일의 확장자가

.a, Microsoft Visual C++의 경우 .lib

15

Standard Library Header File

Standard Library Library File

(16)

Intelligence Networking and Computing Lab.

C Standard Library

❖ C Standard Library

▪ C언어에서 기본적으로 사용할 수 있는 서비스 함수 :

▪ 어떤 함수들이 있나?, 어떻게 이용하나? : 설명서  Reference

• Reference의 예 :

Java API Documentation

▪ C Language/Standard Library Reference

• MS Visual Studio의 경우 통합 개발 환경에서 Reference 이용이 쉽고 설명도 충실함.

– Microsoft는 MSDN(Microsoft Developer Network)라는 Reference DB를 90년대 초반부터 구축 – Visual Studio가 Visual C++이라는 C/C++ 기반 IDE를 기원으로 하여 C 지원 기능이 우수 – 인터넷 브라우저를 통한 접근도 가능

예)https://msdn.microsoft.com/ko-kr/library/59ey50w6.aspx

• Eclipse도 통합 개발 환경에서 C Reference 이용이 가능하나 상대적으로 부실함

– Eclipse는 Java로 개발된 개발 환경으로 Java 개발 IDE로 널리 알려져 있음

• 모든 표준 함수와 그 활용법을 익히고 기억할 수 없음(?). 또 보통은 그럴 필요도 없음.

• 인터넷에서 이용할 수 있는 자신만의 Reference 구하고 즐겨찾기로 지정하고 상시 활용

– Ex1) https://en.wikibooks.org/wiki/C_Programming/Standard_libraries

– Ex2) http://en.cppreference.com/w/c

– Ex3) https://www-s.acm.illinois.edu/webmonkeys/book/c_guide/

▪ Reference 이용 습관 및 활용 역량 배양 !!!  간과하기 쉬운 프로그래밍의 기초

16

(17)

Intelligence Networking and Computing Lab.

C Standard Library

17

❖ Stdio.h, math.h에서 제공하는 함수 목록을 확인해보라.

<assert.h> Contains the assert macro, used to assist with detecting logical errors and other types of bug in debugging versions of a program.

<complex.h> A set of functions for manipulating complex numbers. (New with C99)

<ctype.h> This header file contains functions used to classify characters by their types or to convert between upper and lower case in a way that is independent of the u sed character set (typically ASCII or one of its extensions, although implementations utilizing EBCDIC are also known).

<errno.h> For testing error codes reported by library functions.

<fenv.h> For controlling floating-point environment. (New with C99)

<float.h>

Contains defined constants specifying the implementation-specific properties of the floating-point library, such as the minimum difference between two diffe rent floating-point numbers (_EPSILON), the maximum number of digits of accuracy (_DIG) and the range of numbers which can be represented (_MIN, _ MAX).

<inttypes.h> For precise conversion between integer types. (New with C99)

<iso646.h> For programming in ISO 646 variant character sets. (New with NA1)

<limits.h> Contains defined constants specifying the implementation-specific properties of the integer types, such as the range of numbers which can be represented (_

MIN, _MAX).

<locale.h> For setlocale() and related constants. This is used to choose an appropriate locale.

<math.h> For computing common mathematical functions-- seeFurther mathorC++ Programming/Code/Standard C Library/Mathfor details.

<setjmp.h> setjmp and longjmp, which are used for non-local exits

<signal.h> For controlling various exceptional conditions

<stdarg.h> For accessing a varying number of arguments passed to functions.

<stdbool.h> For a boolean data type. (New with C99)

<stdint.h> For defining various integer types. (New with C99)

<stddef.h> For defining several useful types and macros.

<stdio.h> Provides the core input and output capabilities of the C language. This file includes the venerable printf function.

<stdlib.h> For performing a variety of operations, including conversion, pseudo-random numbers, memory allocation, process control, environment, signalling, searchi ng, and sorting.

<string.h> For manipulating several kinds of strings.

<tgmath.h> For type-generic mathematical functions. (New with C99)

<time.h> For converting between various time and date formats.

<wchar.h> For manipulating wide streams and several kinds of strings using wide characters - key to supporting a range of languages. (New with NA1)

<wctype.h> For classifying wide characters. (New with NA1)

(18)

Intelligence Networking and Computing Lab.

C Standard Library

❖ 다음은 math.h의 exp(), log() 함수를 활용하려는 코드이다.

▪ 아래 코드를 Build하면 Syntax Error 또는 Warning이 발생한다.

• 그 원인을 설명해보라.

▪ 이 문제를 해결하려면 어떻게 해야 하는가? 아래 코드를 수정하라.

18

#include <stdio.h>

int main(void) {

double x = 3.0;

double y, z;

y = log(x);

z = exp(x);

printf("log(x)=%f, exp(x)=%f\n", y, z);

return 0;

}

(19)

Intelligence Networking and Computing Lab.

C Standard Library

❖ <math.h> 파일을 찾아서 그 내용을 살펴보라.

▪ MinGW의 Math.h에는 다음과 같은 Macro가 정의되어 있다.

▪ M_PI가 의미하는 것은 무엇일까?

▪ Header File에는 (서비스) 함수 원형 외에 함수 이용 등에 필요한 Macro나 구조체가 정의되어 있음

19

#define M_E 2.7182818284590452354

#define M_LOG2E 1.4426950408889634074

#define M_LOG10E 0.43429448190325182765

#define M_LN2 0.69314718055994530942

#define M_LN10 2.30258509299404568402

#define M_PI 3.14159265358979323846

#define M_PI_2 1.57079632679489661923

#define M_PI_4 0.78539816339744830962

#define M_1_PI 0.31830988618379067154

#define M_2_PI 0.63661977236758134308

#define M_2_SQRTPI 1.12837916709551257390

#define M_SQRT2 1.41421356237309504880

#define M_SQRT1_2 0.70710678118654752440

(20)

C Standard Library

❖ rand()함수에 대한 다음 Reference Page를 읽고 물음에 답하라.

▪ 이 함수를 이용하려면 어떤 Header File을 include 해야할까?

▪ 이 함수의 Return Type은?

▪ 이 함수 호출에 필요한 매개 인자는?

▪ 이 함수의 역할은?

▪ RAND_MAX라는 Macro의 의미는?

▪ srand()라는 함수는 어떤 역할을 하는가?

▪ srand() 함수를 호출하지 않고 rand()를 호출하면 어떤 영향이 있는가?

20

(21)

Intelligence Networking and Computing Lab.

C Standard Library

❖ 아래 좌측과 우측 코드는 srand() 라인의 실행 여부에만 차이가 있다.

❖ 두 프로그램을 여러 번 실행 시키면서 그 차이를 확인하라.

21

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main(void) {

int i,ranval;

srand(time(0));

for (i=0; i<10; i=i+1) { ranval = rand();

printf("Random value on [0,%d]: %d\n", RAND_MAX, ranval);

}

return 0;

}

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main(void) {

int i,ranval;

// srand(time(0));

for (i=0; i<10; i=i+1) { ranval = rand();

printf("Random value on [0,%d]: %d\n", RAND_MAX, ranval);

}

return 0;

}

(22)

Intelligence Networking and Computing Lab.

C Standard Library

❖ X~Uniform[0,1]

▪ Uniform Random Variable (또는 Uniform Distribution)은 0과 1사이의 실수 값 을 같은 확률로 Random하게 가지는 변수(분포)이다.

▪ 아래 예제의 빈칸을 채워 이용하여 Uniform Random을 따르는 값 10개를 출력 해보라.

22

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main(void) {

int i,ranval;

double uranval;

srand(time(0));

for (i=0; i<10; i=i+1) { ranval = rand();

uranval = [ 1 ];

printf(“Uniform random value on [0,1]: %f\n", uranval);

}

return 0;

}

(23)

Intelligence Networking and Computing Lab.

타입 변환 : Type Casting

❖ 값의 Type을 변경시키는 것

▪ Implicit (묵시적) Type 변경과 Explicit(명시적) Type 변경 두 가지로 분류

▪ Type Casting Operator : 명시적(Explicit)/강제적으로 값의 Type을 변경하는 것

• 오른쪽 코드의 출력 결과는 ?

23

#include <stdio.h>

int main(void) {

int n = 2;

double r = 3.14;

r = n; // 정수 값을 실수 값으로 묵시적 변환 return 0;

}

#include <stdio.h>

int main(void) {

int n = 2;

double r = 3.14;

n = r; // 실수 값을 정수 값으로 묵시적 변환

// 바람직하지 않은 변환으로 Warning이 발생하기도 함

return 0;

}

#include <stdio.h>

int main(void) {

int a = 2, b = 4;

double r1, r2;

r1 = a/b;

r2 = (double)a/b;

printf("%f %f\n", r1, r2);

return 0;

}

(type) expression

(24)

Intelligence Networking and Computing Lab.

C Standard Library

▪ 주사위를 던지기를 Simulation하고자 한다. N_DICE 만큼 주사위 던지기를 한다.

▪ 각 주사위 던지기의 결과 ({1, 2, 3, 4, 5, 6} 중의 한 정수를 같은 확률로 random하게 가짐)를 출력하는 프로그램을 아래 예제를 활용하여 작성하라.

Urand() 함수는 [0, 1) 사이의 실수 값을 Random하게 생성하는 Uniform Pseudo Random Number 생성한다.

나누는 값을 (RAND_MAX+1)로 하여 1.0이 결과가 되지 않는 점에 유의하라.

[ 1 ]에 적당한 expression을 작성하라. expression [ 1 ]에는 urand() 함수 호출이 포함된다.

• 필요하면 math.h의 ceil() 함수를 사용하여도 되며 명시적 type casting을 권장한다.

24

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <math.h>

#define N_DICE 10 double urand(void) {

return (double)rand()/(RAND_MAX+1);

}

int main(void) {

int i, diceval;

srand(time(0));

for (i=0; i<N_DICE; i=i+1) { diceval = [ 1 ];

printf("%dth Dice Value : %d\n", i, diceval);

}

return 0;

}

(25)

배열의 초기화

25

int main(void) {

int i;

int a[3]; //a[0],a[1],a[2]

a[0] = 2;

a[1] = 9;

a[2] = 8;

for (i=0; i<3; i=i+1) printf("%d\n",a[i]);

return 0;

}

int main(void) {

int i;

int a[3]={2,9,8};

for (i=0; i<3; i=i+1) printf("%d\n",a[i]);

return 0;

}

(26)

C Standard Library

❖ 주사위 던지기 Simulation 2

▪ N_DICE 만큼 주사위 던지기를 한 후 각 눈의 값이 실제 나온 횟수를 int 배열 N[6]에 저장 한다.

[1]의 내용은 Simulation 1의 [1]과 같다.

N[0]에는 1이 나온 횟수를, N[1]에는 2가 나 온 횟수를…

▪ N[i]를 N_DICE로 나누면 실제 Simulation 결 과 각 눈이 나온 확률이 되는데 이를 double 배열 P[6]에 저장하라. 이어 그 값을 printf()를 통해 출력하라.

P[0]에는 1의 확률, P[1]에는 2의 확률, …

▪ N_DICE 값을 100, 1000, 10000, 100000 등으 로 증가 시키면서 P[]의 값을 이론적 확률 1/6

~ 0.166667과 비교해 보라.

26

#define N_DICE 100 double urand(void) {

return (double)rand()/(RAND_MAX+1);

}

int main(void) {

int i,diceval;

int N[6]={0,0,0,0,0,0};

double P[6];

srand(time(0));

for (i=0; i<N_DICE; i=i+1) { diceval = [ 1 ];

N[diceval-1] = N[diceval-1]+1;

}

for (i=0; i<6; i=i+1) { P[i] = [ 2 ];

printf("Pr(Dice=%d) == %f\n", (i+1), P[i]);

}

return 0;

}

(27)

Intelligence Networking and Computing Lab.

Monte-Carlo Simulation을 통한 𝜋 구해 보기

❖ Monte-Carlo Method/Simulation

▪ 다수의 Sample/실험으로부터 실제 값 추정하는 법

▪ http://en.wikipedia.org/wiki/Monte_Carlo_methods

❖ Monte Carlo Method를 이용한 𝜋 값 구하기

▪ 오른쪽 그림과 같은 단위 원의 직각 부채꼴을 생각해보자. 부채꼴의 넓이는?

▪ X~Uni(0,1), Y~Uni(0,1)을 따르는 확률변수 쌍 (X,Y)를 생각하자.

▪ (X,Y)의 Sample이 부채꼴 내에 속할 확률은 얼마인가?

• 부채꼴의 면적 / 정사각형의 면적 = 𝜋/4

▪ 전체 Sample 중 실제 부채꼴 내에 존재하는 Sample의 수는 몇 개인가?

• # of Samples inside the circle / # of total samples ≈ 𝜋/4

▪ Sample의 수를 증가시키면서 위 값의 변화를 확인하라.

27

(28)

Intelligence Networking and Computing Lab.

Monte-Carlo Simulation을 통한 𝜋 구해 보기

❖ 코드 구조

▪ 실험을 통해 유도할 𝜋 값을 위한 double 변수 monte_pi를 정의하라.

▪ 부채꼴 내의 (경계 포함) 점의 수, 외부의 점의 수를 의미하는 int num_in과 num_out을 정의 하고 0으로 초기화하라.

▪ 생성할 (x,y) 좌표의 수를 의미하는 정수 값을 입력 받아 저장할 int 변수 n에 저장하라.

• 입력 값이 0보다 작거나 같은 경우에 n의 값을 1000000으로 설정하라.

▪ [0, 1] 사이의 random한 값을 가지게 될 double 형 변수 x, y를 정의하라.

• (x,y)는 하나의 좌표 sample에 해당한다.

▪ for Loop을 활용하여 n 개 점을 random하게 생성하고 각 점이 부채꼴 내부인지, 외부인지 판정하고 그 결과에 따라 num_in 또는 num_out 값을 변경하라.

• 내부인지 외부인지 어떻게 판정할 수 있을까?

• 경계 위의 점들도 내부로 판정한다.

▪ For Loop이 종료되면 monte_pi 값을 구하고 printf를 통해 출력하라.

• %f 가 아닌 %.20f 를 사용하여 소수 이하 20자리까지 출력되도록 하라.

28

(29)

Monte-Carlo Simulation을 통한 𝜋 구해 보기

29

#define N_MAX 1000000 int main(void)

{

double monte_pi, x, y;

int num_in=0, num_out=0;

int n, i;

srand(time(0));

scanf("%d",&n);

[ 1 : n 값을 조건에 맞게 필요하면 변경하라]

for (i=0; i<n; i=i+1) {

[ 2 : [0,1] 사이의 값을 random하게 갖는 x, y값을 구하라. ] [ 3 : x, y 값을 활용하여 부채꼴 내부인지 여부를 판정하고

num_in, num_out 값을 조정하라 ] }

monte_pi = [ 4 : monte_pi 값을 유도하라. ]

printf("Monte-Carlo PI = %.20f, (Number of Sample = %d)\n",monte_pi,n);

return 0;

}

(30)

Intelligence Networking and Computing Lab.

User Library의 이용

❖ User Library

▪ Standard Library 외에 여러 개발자들이 제작하여 배포하는 Library

▪ Source를 공개하는 경우도 있고 그렇지 않은 경우도 있음

• Source가 없더라도 활용은 가능함

❖ Test Library Download

▪ 자신의 Workspace 폴더에 UserLibrary라는 폴더를 만들고 PLMS 홈 페이지에서 pnu_lib.h와 lib_pnulib.a를 다운로드하여 저장

▪ Pnu_lib.h의 내용은 아래와 같으며 pnu_square()와 pnu_circle()이라는 두 함수를 제공하는데 이전에 my_lib.h의 square()와 circle()과 각각 동일한 기능을 제공함

30

#ifndef PNU_LIB_H_

#define PNU_LIB_H_

double pnu_square(double a);

double pnu_circle(double r);

#endif /* PNU_LIB_H_ */

(31)

Intelligence Networking and Computing Lab.

User Library의 이용

❖ “my_lib.h”/mymath.c 를 활용하던 기존 코드를 주어진 pnu_lib 라이 브러리를 이용하도록 수정 작성하라.

▪ pnu_square(), pnu_circle()을 호출하기 위해서는 소스 코드를 어떻게 수정하여야 하는가?

• #include “pnu_lib.h”의 추가

• Syntax Error의 발생 :

..\main.c:3:21: fatal error: pnu_lib.h: No such file or directory

31

#include <stdio.h>

#include "my_lib.h"

int main(void) {

double x=2.5;

double y,z;

y=square(x);

z=circle(x);

printf("%f, %f\n", y, z);

return 0;

}

main.c

#include <stdio.h>

#include "my_lib.h"

int main(void) {

double x=2.5;

double y,z;

y=pnu_square(x);

z=pnu_circle(x);

printf("%f, %f\n", y, z);

return 0;

}

main.c

(32)

Intelligence Networking and Computing Lab.

Include Path의 지정

❖ #include로 포함시키고자 하는 폴더(경로)를 설정하여야 함

▪ Project Explorer의 “Includes”에는 현재 지정된 폴더(경로)가 나타남

▪ 프로젝트 Properties를 열어 GCC Compiler의 Include 항목 수정

▪ Include Path 추가

• 이전 에러 해결

▪ 새로운 에러

32 클릭하여 다운로드한 경로를 찾아 선택

J:\eclipse\workspace\CProject3\Debug/../main.c:9: undefined reference to `pnu_square' J:\eclipse\workspace\CProject3\Debug/../main.c:10: undefined reference to `pnu_circle'

(33)

Intelligence Networking and Computing Lab.

Library의 지정

❖ Linking Error

▪ 아래 에러는 Compile 시의 Syntax Error가 아니라 Linking할 Object 파일을 찾지 못했음을 의미함

❖ Library Path와 Library 이름 지정이 필요

▪ 프로젝트의 Properties 열어 C Linker의 Libraries 설정 변경

▪ Library search path를 설정

• Include path 설정 방식과 동일

▪ Libraries에서 사용할 Library 이름 지정

• 다운로드한 라이브러리 파일 libpnu_lib.a 에서 접두어 lib과 확장자 .a를 제외한

pnu_lib을 지정

▪ Standard Library의 경우 별도 지정하지 않더라도 Linker가 기본 포함

33 J:\eclipse\workspace\CProject3\Debug/../main.c:9: undefined reference to `pnu_square'

J:\eclipse\workspace\CProject3\Debug/../main.c:10: undefined reference to `pnu_circle'

참조

관련 문서

intensive properties are available. • The calculation of these properties from measurable ones depends on the availability of simple and accurate relations between the two

Moving from Traditional Payment Rails to Payment Networks 73 Fiat Currency Stablecoins Create More Interoperability between Ecosystems 74 Cryptocurrency and

1 John Owen, Justification by Faith Alone, in The Works of John Owen, ed. John Bolt, trans. Scott Clark, &#34;Do This and Live: Christ's Active Obedience as the

I n the present study, DBD plasma actuator with an electrically floating electrode was designed. The effects of the floating electrode configuration on

In gi ngi va,LCs are found i n oralepi thel i um ofnormalgi ngi va and i n smal l er amountsi nthesul cul arepi thel i um,buttheyareprobabl yabsentfrom thejuncti onal epi thel

FPSO (Floating Production Storage &amp; Offloading) FSO(floating storage and offloading).. FSRU (Floating Storage Regasification

Type 2 The number of lines degenerate to a point but there is no degeneration of two dimensional phase regions.. Non-regular two-dimensional sections.. Nodal plexi can

Type 2 The number of lines degenerate to a point but there is no degeneration of two dimensional phase regions.. Non-regular two-dimensional sections.. Nodal plexi can