hello everyone

I write project, there is problem in linking of my code

Error	1	error LNK2005: _str_list already defined in file1.obj	string-test\file2.obj	string-test
Error	2	error LNK2005: _str_list already defined in file1.obj	string-test\str.obj	string-test

think this is my code, anybody have any idea

main.c

int main()
{
	print1();
	print2();

	return 0;
}

str.c

#include "str.h"

char *get_str(int i)
{
	return str_list[i];
}

str.h

#ifndef __HEADER_STR__
#define __HEADER_STR__

char *str_list[] = { "text1", "text2", "text3" };

char *get_str(int i);

#endif

file1.c

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

void print1(void)
{
	printf("%s\n", get_str(0));
}

file1.h

#ifndef __HEADER_1__
#define __HEADER_1__

void print1(void);

#endif

file2.c

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

void print2(void)
{
	printf("%s\n", get_str(1));
}

file2.h

#ifndef __HEADER_2__
#define __HEADER_2__

void print2(void);

#endif

thanks

Dani AI

Generated

As correctly pointed out, LNK2005 is caused by defining the same object in more than one translation unit. In ’s case the array is being defined inside the header, so every .c that includes that header gets its own definition. Header guards only stop multiple inclusion inside a single translation unit; they do not prevent duplicate definitions across different object files.

Two safe fixes (pick one):

  • Encapsulate the array in str.c (recommended): keep the array file-local and expose only accessors. This avoids any need for an externally visible symbol.
/* str.c — keep the array private */
static const char * const str_list[] = { "text1", "text2", "text3" };

/* get_str stays in this file and returns str_list[i] */
  • Or declare it extern in the header and define it in exactly one .c file if multiple files must access it directly:
/* str.h */
extern const char * const str_list[];
const char *get_str(int i);

/* str.c */
const char * const str_list[] = { "text1", "text2", "text3" };

Additional notes: prefer const char * for string literals to avoid accidental modification. If only read access is required, prefer the static/encapsulation approach and provide a get_str (and possibly a str_count) function to keep the interface clean. Ensure main.c includes the appropriate prototypes (file1.h, file2.h) so calls are checked by the compiler. After making the change, do a full rebuild; the linker error will disappear once there is only a single definition with external linkage.

Never define variables in a header file (.h)
They go into source files (.c)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.