2

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

Community
  • 1
  • 1
Marius
  • 39
  • 6

1 Answers1

2

Not sure how geany works, but the basic stages (on command line) are:

  1. Compile functions.cpp: g++ -c functions.cpp
  2. Compile main.cpp: g++ -c main.cpp
  3. Link them into an executable: g++ -o myprog functions.o main.o

From geany manual, it seems that build works only for one-file programs (bold is mine):

For compilable languages such as C and C++, the Build command will link the current source file's equivalent object file into an executable. If the object file does not exist, the source will be compiled and linked in one step, producing just the executable binary.

and

If you need complex settings for your build system, or several different settings, then writing a Makefile and using the Make commands is recommended; this will also make it easier for users to build your software

The working makefile for the problem would be:

Makefile :

objects = main.o functions.o

AddingNumbersExe : $(objects)
    g++ -o AddingNumbersExe $(objects)

main.o : main.cpp functions.h
    g++ -c main.cpp

functions.o : functions.cpp functions.h
    g++ -c functions.cpp

.PHONY : clean
clean : 
   -rm AddingNumbersExe $(objects)

After creating this file, the "make" option (Ctrl + F9) in geany works.

So to handle your two-file programs you'll need a Makefile or a more powerful IDE.

jsantander
  • 4,972
  • 16
  • 27