Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual C++ unresolved external symbol (can't find one of my own functions)

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.

like image 324
Obediah Stane Avatar asked Dec 04 '22 16:12

Obediah Stane


1 Answers

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.

like image 106
korona Avatar answered Dec 31 '22 02:12

korona