Reputation: 25
In C++, I'm trying to implement an enum to be accepted as a parameter in a method and consistently receive linking errors (undefined reference). Let me provide my header, implementation, and sample main execution. Also note that I am using a Makefile and can provide that if you believe the issue to be within the Makefile.
Header:
// Make sure definitions are only made once
//
#ifndef MYTEST_H
#define MYTEST_H
// System include files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Declare class definitions
//
class MyTest {
// Public data
//
public:
// Define debug_level choices
//
enum DBGL {FULL = 0, PARTIAL, BRIEF, NONE};
// Define a debug_level variable
//
static DBGL debug_level_d;
// Define public method set_debug that sets debug level to a specific value
//
bool set_debug(DBGL x_a);
// End of include file
//
#endif
Here is my implementation file 'mytest_00.cc'. Here, I am attempting to define an enum type "DBGL" as the debug level. And then I am trying to accept that as a parameter in the method 'set_debug'.
#include "mytest.h"
// Implementations of methods in MyTest
// Declare debug_level
//
static MyTest::DBGL debug_level_d = MyTest::FULL;
// Implement set_debug method to set the debug_level_d
// FULL = 0, PARTIAL = 1, BRIEF = 2, NONE = 3
//
bool MyTest::set_debug(MyTest::DBGL x_a) {
// Set debug_level_d to the argument provided
//
debug_level_d = x_a;
// exit gracefully
//
return true;
}
The goal is to test the class 'mytest' in the main function by executing something like:
MyTest Test;
Test.set_debug(FULL);
And this code would set the variable 'debug_level_d' as the parameter passed.
The error I receive upon compilation is as follows:
g++ -O2 -c mytest.cc -o mytest.o
g++ -O2 -c mytest_00.cc -o mytest_00.o
g++ -g -lm mytest.o mytest_00.o -o mytest.exe
mytest_00.o: In function `MyTest::set_debug(MyTest::DBGL)':
mytest_00.cc:(.text+0x12): undefined reference to `MyTest::debug_level_d'
collect2: error: ld returned 1 exit status
make: *** [mytest.exe] Error 1
Any help in understanding why this error is occurring would be greatly appreciated. I've been stuck on this for a day now. Please let me know if any details require further clarification.
Thank you.
Upvotes: 0
Views: 143
Reputation: 1471
You should not use the static keyword when defining the field in the .cpp file, only when declaring it in the class. Note in the code comments you have "declaring" and "defining" the wrong way round.
Additionally, when defining the member, you need to qualify it with the class name.
So the .cpp definition should be:
MyTest::DBGL MyTest::debug_level_d = MyTest::FULL;
By using the static keyword in the definition, you restrict it to internal linkage.
See: http://en.cppreference.com/w/cpp/language/static
Upvotes: 1