Reputation: 95
When I try to compile my program with header file in gcc I get error like this: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\37069\AppData\Local\Temp\ccnYwij4.o:file2048.c:(.bss+0x0): multiple definition of `matrix'; C:\Users\37069\AppData\Local\Temp\ccGaOCe4.o:namudarbas2.c:(.bss+0x0): first defined here collect2.exe: error: ld returned 1 exit status
matrix is only initialized in my header file.
Header file:
#ifndef FILE2048_H
#define FILE2048_H
#define SIZE 4
#ifdef __cplusplus
extern "C" {
#endif
int matrix[SIZE+1][SIZE+1]={0};
int score;
void saveToFile(void);
void start(void);
void reset(void);
#ifdef __cplusplus
}
#endif
#endif
Other file with function defined:
#include <stdio.h>
#include <stdlib.h>
#include "file2048.h"
void saveToFile(){
FILE *load=fopen("2048.txt", "w");
fprintf(load, "%d %d %d %d\n%d %d %d %d\n%d %d %d %d\n%d %d %d %d\n%d", matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3], score);
fclose(load);
}
void start(){
FILE *load=fopen("2048.txt", "r");
int i, j;
for(i=0; i<SIZE; i++){
for(j=0; j<SIZE; j++){
fscanf(load, "%d", &matrix[i][j]);
}
}
fscanf(load, "%d", &score);
fclose(load);
}
And a bit of my main file, where I try calling the function I created in my other file:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <conio.h>
#include "file2048.h"
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
#define ESC 57
int over=0;
int last=0;
void display(){
system("cls");
int i, j;
for(i=0; i<SIZE; i++){
printf("\n\n\n");
for(j=0; j<SIZE; j++)
{
printf("%d\t", matrix[i][j]);
}
}
saveToFile();
printf("Your score - %d", score);
}
Any help where the problem could be? I'm new with header files.
Upvotes: 3
Views: 1138
Reputation: 493
Your header file file2048.h
contains variable declarations. When you include this file in other sorces files this causes the variable to be declader multiple times. Please look into the extern
keyword.
Header File:
#ifndef FILE2048_H
#define FILE2048_H
#define SIZE 4
#ifdef __cplusplus
extern "C" {
#endif
/* - Bad implementation
int matrix[SIZE+1][SIZE+1]={0};
*/
//Better implementation
extern int matrix[SIZE+1][SIZE+1];
//Now define this variable only once, on "main.c" for example
.
.
.
#endif
Upvotes: 3