programing

링크하는 동안 전역 변수에 대한 정의되지 않은 참조

minimums 2023. 10. 15. 17:11
반응형

링크하는 동안 전역 변수에 대한 정의되지 않은 참조

3개의 소스 파일에 해당하는 3개의 모듈로 나누어진 프로그램을 컴파일하려고 합니다.a.c,b.c,그리고.z.c.z.c포함.main()함수, 함수를 호출합니다.a.c그리고.b.c. 게다가, 에 있어서의 함수.a.c함수를 호출합니다.b.c,그리고 역도 성립.마지막으로 글로벌 변수가 있습니다.count세 개의 모듈에서 사용되며 별도의 헤더 파일에 정의됩니다.global.h.

소스 파일의 코드는 다음과 같습니다.

a.c

#include "global.h"
#include "b.h"
#include "a.h"

int functAb() {
    functB();
    functA();
    return 0;
}

int functA() {
    count++;
    printf("A:%d\n", count);
    return 0;
}

b.c

#include "global.h"
#include "a.h"
#include "b.h"

int functBa() {
    functA();
    functB();
    return 0;
}

int functB() {
    count++;
    printf("B:%d\n", count);
    return 0;
}

z.c

#include "a.h"
#include "b.h"
#include "global.h"

int main() {
    count = 0;
    functAb();
    functBa();
    return 0;
}

헤더 파일:

a.h

#ifndef A_H
#define A_H

#include <stdio.h>

int functA();
int functAb();

#endif

b.h

#ifndef B_H
#define B_H

#include <stdio.h>

int functB();
int functBa();

#endif

global.h

#ifndef GLOBAL_H
#define GLOBAL_H

extern int count;

#endif

그리고, 마지막으로,makefile내 실수를 반복하는군요

CC = gcc
CFLAGS = -O3 -march=native -Wall -Wno-unused-result

z:  a.o b.o z.o global.h
    $(CC) -o z a.o b.o z.o $(CFLAGS)
a.o:    a.c b.h global.h
    $(CC) -c a.c $(CFLAGS)
b.o:    b.c a.h global.h
    $(CC) -c b.c $(CFLAGS)
z.o:    z.c a.h global.h
    $(CC) -c z.c $(CFLAGS)

이것으로 나는 물체들을 컴파일 할 수 있습니다.a.o,b.o,그리고.z.o좋아요, 하지만 링크할 때는make z, 알겠습니다.undefined reference to 'count'그들 모두에게:

z.o: In function `main':
z.c:(.text.startup+0x8): undefined reference to `count'
a.o: In function `functAb':
a.c:(.text+0xd): undefined reference to `count'
a.c:(.text+0x22): undefined reference to `count'
a.o: In function `functA':
a.c:(.text+0x46): undefined reference to `count'
a.c:(.text+0x5b): undefined reference to `count'
b.o:b.c:(.text+0xd): more undefined references to `count' follow
collect2: ld returned 1 exit status

이 최소한의 예제에서 제 실제 코드의 오류를 재현할 수 있어서 모듈 간의 의존성에 문제가 있는 것 같습니다.누가 제게 올바른 방향을 가르쳐 줄 수 있습니까?

변경합니다.z.c로.

#include "a.h"
#include "b.h"
#include "global.h"

int count; /* Definition here */
int main() {
    count = 0;
    functAb();
    functBa();
    return 0;
}

부터global.h, 당신의 모든 파일은 변수 선언을 이어받습니다.count모든 파일에 정의가 빠져 있습니다.

다음과 같이 정의를 파일 중 하나에 추가해야 합니다.int count = some_value;

카운트를 선언한 것이지 정의한 것이 아닙니다.

extern정의가 아닌 선언의 일부입니다.

분명히 말씀드리면,extern는 스토리지 클래스 지정자이며 선언 시에 사용됩니다.

정의해야 합니다. int count소스 파일 어딘가에 있습니다.

추가해야 합니다.int count;당신의 z.c 파일로.이것은 헤더 파일의 변수를 다음과 같이 선언하기 때문입니다.extern는 컴파일러에게 변수가 다른 파일에 선언될 것임을 알려주지만, 변수는 아직 선언되지 않았으며 블랭커로 해결될 것입니다.

그러면 어딘가에서 변수를 선언해야 합니다.

언급URL : https://stackoverflow.com/questions/28090281/undefined-reference-to-global-variable-during-linking

반응형