
-----------------------------------
Srlancelot39
Thu Jul 10, 2014 11:46 am

error LNK2005: _Function already defined in student.obj
-----------------------------------
I have a C project with 3 files: a .c file with main(), a header file, and another .c file containing functions.
main() calls functions in the .c file containing the functions.
This .c file #includes the header file which contains a structure used by the functions as well as by main().

My header file is surrounded with
#ifndef header_h
#define header_h
//header code
#endif

however, I get the error: error LNK2005: _Function already defined in student.obj
as well as: error LNK1169: one or more multiply defined symbols found
(I assume the second is related to the first.)

Apparently, according to other sources, this is due to the function being compiled twice.  I am not sure what would be causing that though since that file is only #included once (by main()).

What am I doing wrong or missing?  What is the correct way to use structures and functions across multiple files?

Thanks!

EDIT: I removed the #include for the .c file and added function declarations before main() and it now seems to work!  Is the lesson here, "Don't #include .c files"?

-----------------------------------
DemonWasp
Thu Jul 10, 2014 4:59 pm

RE:error LNK2005: _Function already defined in student.obj
-----------------------------------
That's basically the lesson.

The overall idea is that there may be several different implementations of a header (.h, .hpp, etc) file. For example, you might have a Windows version and a GNU/Linux version; or you might have a real version and a mocked version (for testing).

Your code should only #include header files because the header files should contain only the interface for each module. The choice of which implementation to use occurs at compile-time.

...I think. I don't program C/C++ much.

-----------------------------------
Srlancelot39
Fri Jul 11, 2014 9:00 am

RE:error LNK2005: _Function already defined in student.obj
-----------------------------------
That sounds about right.  Okay, thanks!
