Friday, May 21, 2010

/C++/ Linker error. I'm at my wit's end, to the point of insanity.?

For some idiotic reason my professor is making us include source files in our source files. The way I have it set up is test.cpp has my int main, t1.cpp has my class t1 function definitions, t1.h has my t1 class declaration, s1.cpp has my class s1 function definitions, and s1.h has my s1 class declaration.





Assuming that they were all in one file, the order would go:





s1.h


s1.cpp


t1.h


t1.cpp


test.cpp.





Therefore, I have linked them together like so





test.cpp includes t1.cpp


t1.cpp includes t1.h


t1.h includes s1.cpp


s1.cpp includes s1.h





I don't get any compiler errors, but the linker gives me this really irritating message.





"Multiple definition of (blahblahblahetcetc)


first defined here" over and over and over again, all down the screen.





I'm at my wit's end, I've tried linking them every human way possible, it just isn't working.





If someone could please prevent me from going insane and help me, I would greatly appreciate it.

/C++/ Linker error. I'm at my wit's end, to the point of insanity.?
Yes, that's a bad practice. But of course, your prof probably has some sort of lesson in this for you. Some suggests:





1. Make sure you tell the compiler to only compile %26amp; link test.cpp. (because everything else is #included)





2. Ordering *is* important. You should know that the 1st time the compiler parses a function or class, _that_ is where it gets defined for the compiler. If the compiler sees it again somewhere...even in an H file, then that's a re-definition and you see the "Multiple definition for..." error.





Therefore, make every attempt to ensure that the first time the compiler "sees" a function, it's seeing the function prototype before it encounters a call to the function. Try to order things so the H files get seen 1st, for example...that will help.





3. If it is permissable according to prof's instructions, I recommend that only test.cpp includes all the other files. No other file says #include.





4. Look in an H file. Note the use of this sysntax in conio.h:





#ifndef _CONIO_H_INCLUDED


#define _CONIO_H_INCLUDED





....body of H file goes in here.





#endif





...this convention prevents the contents of conio.h from being included 2x, even if you #include it 2X or more in your code. This also serves to help prevent the "multiple def..." error
Reply:its been a while since i've done this, but I think you need to have something like this to get it to work


test.cpp includes t1.h,s1.h


t1.cpp includes t1.h


s1.cpp inludes s1.h





.cpp files should never be in the include statements, only .h - headers.
Reply:genefrequency is correct. Also make sure that in your .h files you begin with:


#ifndef VARIABLE


#define VARIABLE





and end your file with #endif

flower arranging

No comments:

Post a Comment