mercredi 11 mars 2015

Pure functions file with header file always resulting in undefined reference

I'm trying to create a general functions file for myself. I want to do it right so no #include .cpp but .h files. However I result in undefined references all the time. I reproduced it with the following three files:


main.cpp :



#include <iostream>
#include "functions.h"
using namespace std;

int main()
{
cout << addNumbers(5,6);
}


functions.h :



#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int addNumbers(int x,int y);

#endif


functions.cpp :



#include "functions.h"

using namespace std;

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


The files are all in one folder. I'm using Linux Mint, geany and c++11. Compiling results in the following error:



main.cpp:(.text+0xf): undefined reference to `addNumbers(int, int)'



Unfortunately I only found similar problems concerning classes online. I have come so far as to understand it is a linking problem though I have no clue about that part of the compiling process. Adding the function to the .cpp before main() or after with prototyping works fine. This question Undefined reference C++ seems to be similar but I don't understand the answers.


My questions are:




  1. How can I solve this? (I do not wish to wrap the functions in a class or add them to the main.cpp)




  2. If possible an explanation as to what is going wrong here.




  3. I am wondering if I could also call specific functions with the :: as I have seen it around but never used it because I don't know how it works.




Thank you


Aucun commentaire:

Enregistrer un commentaire