Search code examples
c++visual-c++header-filesbuild-error

C++ Header #define compiler error


I'm learning C++ and I'm at a fairly low level still. - I'm currently looking at using header files and I have a two part question.

Part 1

As I understand them so far, header file definitions are similar to hard coded strings within VB.net? For example I can do the following #define STOCK_QUANTITY 300 and then reference my definition when using it within functions? I assume this works the same way as VB.net strings as I only need to change the value in one place should I need to make changes to the definition and my program references the number 300 on a few hundred different lines?

Part 2

Now, as I said I'm still learning so I'm still doing ye old multiplication tasks. I'm good within using functions with my main .cpp file but I'm not moving on to header files. This is my code snippet thus far.

add.h

#ifndef ADD_H
#define ADD_H

int add(int x, int y);

#endif 

main.cpp

#include "stdafx.h"
#include <iostream>
#include "add.h"

int main()
{
    using namespace std;
    cout << add(3, 4) << endl;
    return 0;
}

When trying to run this I receive 2 build errors and it will not compile. enter image description here

Apologies is these are silly questions, but I would appreciate insight, tips or even some other things I should consider. Thanks.

EDIT

Based on an answer I've changed my add.h too

#ifndef ADD_H
#define ADD_H

int add(int x, int y)
{
    return x + y;
}

#endif

As soon as I read the answer I realised I hadn't even told the function what to do :( - Gosh.


Solution

  • You have not added a function body for the function add

    int add(int x, int y)
    {
        // add stuff here
    }
    

    This can be done in either the header file, or a seperate cpp file for add. You are trying to call the function that has no code. This is known as a function prototype.