I am using VC++ 2010 Express. I wrote a program that runs correctly. I am writing a follow up program in the same project.
That second program won't compile. I get a Link 2005 Error that says the functions and variables are already defined. The follow up program does use the same functions and variables as the first.
My questions are:
1)
Does a compiler (in VC++, say) compile just the desired source file or ALL the source files in that project?
2)
If I wanted to run just my follow up program, should I have created a new project rather than add a new source file to the existing project? (I suspect yes.)
3)
Is there a way to isolate just 1 source file in a project to compile and run?
4)
When I want to run a multi-file project, do I need only define variables and function in only 1 source file? Can I then call them in other source files in which they are not defined?
I am teaching myself C++ and this is the first time I have encountered this type of Link error. Please be informative in your answers and leave any sarcasm for other forums. Thanks in advance.
1. It compiles the ones that have been changed, but all the compiled files are used in the end.
2. Yes.
3. Yes - just only create the one source file in the project ;)
4. Functions must always only be defined in one place unelss they are inline. This is why in headers you have function prototypes and in source files you have function definitions. Source files that include the header get the prototype so the compiler knows it exists, and then the linker can give the function definition from the outher source files by linking them together (hence its name).
Here's an example of a function defined in one source file and used in another:
1 2 3 4 5 6
//Source1.cpp
int AddTwoNumbers(int a, int b)
{
return a+b;
}
1 2 3 4 5 6 7 8 9 10 11
//Source2.cpp
#include <iostream>
int AddTwoNumbers(int a, int b); //semi-colon means 'defined elsewhere'
//the parameter names "a" and "b" can be left out, only the types are needed
int main()
{
int q = 1, z = 2;
std::cout << AddTwoNumbers(z, q) << std::endl;
}
Thank you for your very informative reply. Your example is a little above me because I am not yet ready to build multi-file projects. But you have helped me to greatly increase my intuitive understanding of that topic.