2023. 1. 6. 21:35ㆍc,c++
extern은 이 코드가 쓰일 것이니 일단 넣어놓고 컴파일하라는 의미이다. header, cpp와 같이 다른 파일과 같이 링크하게 될 때 중복을 피하기 위해서 쓰인다. 왜냐하면 #include 이용 시에는 결국 코드 복사 붙여넣기이기 때문이다.
header에 넣을지 c파일에 넣을지는 목적에 따라 다른데, 보통은 header가 전체적인 코드와 abstract를 보기 편하기 때문에 넣게 된다.
주의할 것은 extern 키워드 이용 시 정의를 하고 다른 파일 쓰일 때는 꼭 정의를 해주어야 한다.
InstructionSet.h
#pragma once
typedef struct
{
int opcode;
int format;
int rs2;
int rs1;
int immediate;
}Instruction;
typedef struct
{
char* name;
int address;
}Text;
/*text symbol*/
extern Text text_symbol_table[424];
void Init();
/* alucontrol input*/
extern int ALU_ADD;
/* control signal */
extern int mem_read;
extern int mem_to_reg;
extern int alu_op;
extern int mem_write;
extern int alu_src;
extern int reg_write;
extern int registers[2];
/*save the data*/
extern char memory[1024];
/*program counter*/
extern int pc;
InstructionSet.c
#include "InstructionSet.h"
#include <string.h>
#include <stdio.h>
char memory[1024];
/* alucontrol input*/
int ALU_ADD = 0b01;
/* control signal */
int mem_read;
int mem_to_reg;
int alu_op;
int mem_write;
int alu_src;
int reg_write;
char instruction1[24] = "000001000000101000000000";
void Init()
{
strncpy_s(memory, sizeof(memory), instruction1, 24);
}
다른 파일에 있는 함수 이용시 foward declaration 을 이용하여 컴파일러한테 어딘가에 있을 것이다라고 알려주는데
그러나 없다면 컴파일은 되어도 메모리가 없어서 에러 , 그리고 초기화를 해주어야 메모리 할당이 된 것이다.
그러나 이름이 extern 써서 같은 것이 있다면 충돌 error 한 군데에서만 초기화 해주고 써야한다.
함수는 extern keyword가 생략되어 있다.
헤더파일을 include 하여 namespace 를 이용하여 계속 불러올 때 계속 새로운 메모리를 할당하여 가져오게 된다.
그것을 방지하기 위해서 한 곳의 메모리만 가져다 쓰기 위해서는 헤더가 아니라 같은 곳에 있는 cpp파일을 하나 만들고 header에서는 extern을 이용해 다른 파일에 있는 것을 읽겠다고 표시해놓고 cpp 파일 한 군데에서 계속 읽어오는 것이다.
'c,c++' 카테고리의 다른 글
Dereferencing null pointer (0) | 2023.10.23 |
---|---|
참조에 의한 인수전달, 주소에 의한 전달 (0) | 2023.01.16 |
#ifdef, endif, #pragma once, #ifndef (0) | 2022.09.19 |
맨날 헷갈리는 assert 함수 (0) | 2022.08.19 |
[C언어] 포인터 및 메모리 정리 (0) | 2022.08.18 |