0

Every single function in my class is giving me this error. I'll throw in my 3 parameter constructor as an example:

#include <iostream>

using namespace std;

class Mixed{
    public:
        Mixed(int i, int n, int d);    
    private:
        int integer, numerator, denominator;
};

and my cpp:

#include "mixed.h"
#include <iostream>
#include <iomanip>

using namespace std;

Mixed::Mixed(int i, int n, int d){
    int valid;
    int negatives = 0;

    if (d == 0){
        valid = 0;
    }
    if (d < 0 | n < 0 | i < 0 && valid != 0){ //if there are any negatives and it hasn't been made invalid
        if (i < 0){ //start counting negatives
            negatives++;
        }
        if (n < 0){
            negatives++;
        }
        if (d < 0){
            negatives++;
        }
        if (negatives > 1){ //invalid if more than one negative value
            valid = 0;
        }
        else {
            valid = 1;
        }

        if (i != 0 && valid != 0){ //check for order if it hasn't already been made invalid
            if (n < 0 | d < 0){ //invalid if integer is non zero, but one of the others is negative
                valid = 0;
            }
        }
        else if (n != 0 && d < 0){ //invalid if integer is zero, numerator is nonzero, and denominator is negative
            valid = 0;
        }
        else if (valid != 0){ //if it hasn't already been invalidated, it's valid
            valid = 1;
        }
    }

    if (valid == 0){
        this -> integer = 0;
        this -> numerator = 0;
        this -> denominator = 0;
    }
    else{
        this -> integer = i;
        this -> numerator = n;
        this -> denominator = d;
    }
}

the main.cpp where my class is being used does contain

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

My errors look like:

/tmp/ccbdj59O.o: In function main': main.cpp:(.text+0x34): undefined reference toMixed::Mixed(int, int, int)'

I'm at my wit's end and it feels like it's an obvious mistake. Thoughts?

1 Answers1

1

You want to compile both cpp files and link them together.

This can be done using g++ with the command

g++ mixed.cpp main.cpp -o output_file

This compiles both files and links them together. You can also do that separately:

g++ -c mixed.cpp -o mixed.o
g++ -c main.cpp -o main.o
g++ main.o mixed.o -o output_file

If you don't know how to use the command line look this tutorial if you are working on Linux (I guess you are, based on the fact that you got a linker error and thus have g++ working). On Windows you will probably want to use an IDE, look here for suggestions.

Looking at your comment you are using Sublime Text to build your files, maybe try opening your working folder (File > Open Folder...) instead of a single file. Anyway I think it's better to know what is happening behind scenes.

Community
  • 1
  • 1
Kevin Peña
  • 712
  • 3
  • 10