views:

4482

answers:

5

This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has

int add(int i, int j)

and the implementation "Add.cpp" which has

int add(int i, int j) {
  return i+j;
}

Now let's say in a second project I want to use the add function. However, this code:

#include "..\SimpleMath\Add.h"

int main() {

    add(1, 2);

}

results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.

+3  A: 

You either have to make Add.cpp part of a library and include it in both projects. or you have to add Add.cpp to your second project too.

Edit: to make SimpleMath a library go into the project settings on General and change the Configuration Type to Static Lib.

Then go into your solution settings, click on Project Dependencies, then select your second project in the drop down list, and put a check mark next to SimpleMath. That will automatically link SimpleMath to your second project, and will also make sure that any changes to SimpleMath will be rebuilt when you rebuild your second project.

Gerald
+1  A: 

SimpleMath would need to be defined as a library file (.LIB) in it's project properties I'm assuming that this is an unmanaged (non-.Net) C++. Then include SimpleMath.lib in the other project.

James Curran
A: 

Have a look at this link, it should help you out:

http://msdn.microsoft.com/en-us/library/0603949d.aspx

Mark Ingram
+2  A: 

The reason for the error you're getting is that by including the header file you're telling the compiler that there is a symbol

int add (int, int)

That will be present during linkage, but you haven't actually included that symbol (the code for the function) in your project. A quick way to resolve the issue is to simply add Add.cpp to both projects. But the "nice" solution would probably be to make SimpleMath into a library instead of an application by changing the project type in the project properties.

And by the way, you probably want some sort of mechanism in place to prevent multiple inclusion of that header file in place. I usually use #pragma once which should be fine if you stick with Visual C++ but that might not be entirely portable so if you want portability, go with the more traditional approach of wrapping the header file in an #ifndef-block, as such:

#ifndef __ADD_H
#define __ADD_H

int add (int i, int j);

#endif

Good luck.

korona
Newer compilers support #pragma once directive; one can use it instead of header guard.
Marcin Gil
A: 

If you're trying to link C libraries into C++ projects, you'll need to do something like

extern "C" {
    #include "..\SimpleMath\Add.h"
}

as C and C++ use different symbol names.