I am under the impression that you are allowed to define member functions of a class in one file and then use those functions in another file, as long as both files are compiled and sent to the linker. However, doing this gives me an undefined reference error if I use g++ (4.6.4). Interestingly, using the intel compiler (icpc 11.0) does not give an error and everything works. Is there some flag I can set in g++ to make this work, or is the intel compiler letting me get away with something I shouldn't be doing? Here is some code that reproduces my problem:
class.h:
#ifndef _H
#define _H
typedef class
{
public:
int a;
int b;
void set(int x, int y);
int add(void);
} Test;
#endif
class.cpp:
#include "class.h"
void Test::set(int x, int y)
{
a = x;
b = y;
}
int Test::add(void)
{
return a+b;
}
main.cpp:
#include <cstdio>
#include "class.h"
int main(void)
{
Test n;
n.set(3, 4);
printf("%d\n", n.add());
return 0;
}
To compile, I do:
$ g++ class.cpp main.cpp -o test
/tmp/ccRxOI40.o: In function `main':
main.cpp:(.text+0x1a): undefined reference to `Test::set(int, int)'
main.cpp:(.text+0x26): undefined reference to `Test::add()'
collect2: ld returned 1 exit status
Okay, this is strange, but what happened is that this construct:
typedef class
{
public:
int a;
int b;
void set(int x, int y);
int add(void);
} Test;
while legal is not being treated semantically the same by the compiler as:
class Test
{
public:
int a;
int b;
void set(int x, int y);
int add(void);
};
The typedef version makes your methods static to the file, as indicated in the nm output:
$ nm class.o
0000000000000024 t _ZN4Test3addEv
0000000000000000 t _ZN4Test3setEii
U __gxx_personality_v0
While the class Test version makes them proper methods:
$ nm class2.o
0000000000000024 T _ZN4Test3addEv
0000000000000000 T _ZN4Test3setEii
U __gxx_personality_v0
This is why the linker failed to find the symbols.
Edit: As to why this is happening, it seems to be due to an issue with interpreting how the Standard specifies the treatment of the typedef name as a class-name. Newer compilers do not seem to exhibit the same issue. The problem reported in this question was reproduced with g++ 4.4.7.
If you move the code in your class.cpp file into main.cpp and only compile main.cpp, things will work. Alternatively, you can inline the method definitions into class.h.
If you want to leave them as separate translation units, you need to change the class.h file so that your class is defined using the class Test way instead of using the typedef on the anonymous class.
Related
Here's a simple set of files that reproduce the problem I'm having:
c.h:
void dummy();
c.cpp:
#include <stdio.h>
extern "C" {
#include "c.h"
}
class Bubu {
public:
static Bubu *getInstance() {
if (_instance == NULL) {
_instance = new Bubu;
}
return _instance;
}
private:
static Bubu *_instance;
};
Bubu *_instance = NULL;
void dummy() {
printf("bubu called\n");
Bubu *ptr = Bubu::getInstance();
}
main.cpp:
extern "C" {
#include "c.h"
}
int main() {
dummy();
return 0;
}
When I compile I get this:
g++ -W -Wall -c c.cpp -o c.o
c.cpp: In function ‘int bubu()’:
c.cpp:24: warning: unused variable ‘ptr’
g++ -W -Wall main.cpp c.o -o main
c.o: In function `Bubu::getInstance()':
c.cpp:(.text._ZN4Bubu11getInstanceEv[Bubu::getInstance()]+0x7): undefined reference to `Bubu::_instance'
c.cpp:(.text._ZN4Bubu11getInstanceEv[Bubu::getInstance()]+0x1d): undefined reference to `Bubu::_instance'
c.cpp:(.text._ZN4Bubu11getInstanceEv[Bubu::getInstance()]+0x24): undefined reference to `Bubu::_instance'
collect2: ld returned 1 exit status
make: *** [main] Error 1
Compilation exited abnormally with code 2 at Tue Dec 15 09:15:21
I've seen the answer to other similar questions but there the problem is either a missing Bubu:: when calling the static method or lack of initialisation of the static member outside the class declaration or missing the extern "C" construct. I'm fairly certain that I'm not making those mistakes ... I'm definitely making other(s).
Can you please explain what's going on?
When you define a static variable inside a class, you have to define it outside the class also. You tried to do this, but
Bubu *_instance = NULL;
will just make a global pointer to Bubu, not instantiate the static one inside the class. You need to use
Bubu *Bubu::_instance = NULL;
to tell the compiler this will be the static variable inside the class.
This question already has answers here:
undefined reference to template function [duplicate]
(2 answers)
Closed 6 years ago.
I keep getting undefined reference when i call the two functions from my template class "add" and "greater" in my main function.
So, i have:
number.h
#ifndef NUMBER_H
#define NUMBER_H
template <class T>
class number {
public:
T x;
T y;
number (int a, int b){
x=a; y=b;}
int add (T&);
T greater ();
};
#endif
number.cpp
#include "number.h"
template <class T>
int number<T>::add (T& rezAdd){
rezAdd = x+y;
return 1;
}
template <class T>
T number<T>::greater (){
return x>y? x : y;
}
And my main file is: resolver.cpp
#include <stdio.h>
#include <stdlib.h>
#include "number.h"
int main (int argc, char **argv) {
int aux;
number<int> c(3,5);
c.add(aux);
printf ("number added [%d]\n", c.add(aux));
printf ("greater number: [%d]\n", c.greater());
return 0;
}
The errors that i keep getting are:
g++ -Wall -o tema1 resolver.cpp number.cpp
/tmp/ccX483J4.o: In function `main':
resolver.cpp:(.text+0x34): undefined reference to `number<int>::add(int&)'
resolver.cpp:(.text+0x47): undefined reference to `number<int>::add(int&)'
resolver.cpp:(.text+0x64): undefined reference to `number<int>::greater()'
collect2: ld returned 1 exit status
make: *** [all] Error 1
Thanks for the help in advance!
I prefer to have all of my functions in the .cpp file, regardless of whether they are template functions or regular functions. And there is a way to do that with some basic #ifndef magic. Here's what you can do:
main.cpp
#include "myclass.hpp"
int main()
{
// ...
}
myclass.hpp
#ifndef MYCLASS
#define MYCLASS
template<class T>
class MyClass
{
T val;
public:
MyClass(T val_);
}
#define MYCLASS_FUNCTIONS
#include "myclass.cpp"
#endif
myclass.cpp
#ifndef MYCLASS_FUNCTIONS
#include "myclass.hpp"
// regular functions:
// ...
#else
// template functions:
template<class T>
MyClass<T>::MyClass(T val_)
:val(val_)
{}
// ...
#endif
Here's how the precompiler sees it. We have two .cpp files.
When we compile main.cpp we:
include myclass.hpp
check that MYCLASS is undefined, and it is
define it
give compiler the definitions of the generated class (from template class)
include myclass.cpp
define MYCLASS_FUNCTIONS
check if MYCLASS_FUNCTIONS is defined, it is
give compiler the definitions of the generated functions (from template functions)
When we compile myclass.cpp
check if MYCLASS_FUNCTIONS is defined, it isn't
include myclass.hpp
check that MYCLASS is undefined, and it is
define it
give compiler the definitions of the class
include myclass.cpp
include myclass.hpp again
this time MYCLASS is defined so do nothing inside, return to myclass.cpp
check if MYCLASS_FUNCTIONS is defined, it is
give compiler the definition of the generated functions (from template functions)
exit include twice
pass to the compiler all the regular functions
Your class is named wrong. Your class is named cai where all your functions belong to a class named number: http://ideone.com/ZayX0c
One more thing.. you cannot have templates in the .cpp file. Template functions/defintions go in the header along with the class declaration. This is the reason for your undefined function error. Non-template functions go in the .cpp.
#include <cstdio>
#include <cstdlib>
template <class T>
class number {
public:
T x;
T y;
number (int a, int b){
x=a; y=b;}
int add (T&);
T greater ();
};
template <class T>
int number<T>::add (T& rezAdd){
rezAdd = x+y;
return 1;
}
template <class T>
T number<T>::greater (){
return x>y? x : y;
}
int main (int argc, char **argv) {
int aux;
number<int> c(3,5);
c.add(aux);
printf ("number added [%d]\n", c.add(aux));
printf ("greater number: [%d]\n", c.greater());
return 0;
}
Move the definitions of the add and greater function templates into your number.h.
Remember that add and greater aren't functions, they're function templates. To create actual functions, the compiler has to instantiate the template for specific types, such as int, and it can only do that if it has access to the template's definition at the point where it discovers that an instance is needed.
When you compile number.cpp, the compiler has access to the templates' definitions, but it doesn't see any code that requires a specific instance (such as number<int>), so it doesn't generate instances.
When you compile resolver.cpp, the compiler sees that it needs to instantiate those templates for the int type, but it can't since it doesn't have their definitions. So it generates "external references", basically notes telling the linker to look for those functions in some other object file.
The result is that the function templates don't get instantiated in either object file — in one because the compiler didn't know that it should, and in the other because it couldn't — so when the linker goes looking for them (to resolve those external references), it can't find them. That's why you get the error.
Moving the template function definitions into the header makes them visible to the compiler while it's compiling main.cpp, so it's able to instantiate those functions for the int type. Function templates typically need to be defined in header files, rather than .cpp files, for exactly this reason.
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
"undefined reference" to a template class function
(4 answers)
Closed 9 years ago.
See my demo code below:
b.hpp:
#ifndef B_HPP
#define B_HPP
namespace debug {
class test {
public:
template <class T> void foo(T a);
private:
int a;
};
}
#endif
b.cpp:
#include <iostream>
#include "b.hpp"
namespace debug {
template <class T>
void test::foo(T a) {
std::cout << "debug" << std::endl;
}
}
testb.cpp:
include "b.hpp"
int main(int agrc, char *argv[])
{
debug::test a;
int c = 5;
a.foo(c);
return 0;
}
I compile it with
g++ -std=c++11 testb.cpp b.cpp'
and get a error:
/tmp/ccnjR5S4.o: In function `main':
testb.cpp:(.text+0x1c): undefined reference to `void debug::test::foo<int>(int)'
collect2: error: ld returned 1 exit status
What's the problem?
If I put main function in b.cpp and compile b.cpp, it 's ok. Why?
Thanks!
This is one of the cases where you need explicit instantiation, or to move code back into b.hpp. This arises because the implementation of debug::test::foo isn't visible when you compile testb.cpp, and the compiler has no way of knowing what might be needed when it compiles b.cpp.
To explicitly instantiate debug::test::foo<int>, add the following line to b.cpp:
#include <iostream>
#include "b.hpp"
namespace debug {
template <class T>
void test::foo(T a) {
std::cout << "debug" << std::endl;
}
// Explicitly instantiate test::foo<int>
template void test::foo<int>(int); // <-- add this line
}
Alternately, if you do not know all the ways this template might get instantiated, move its definition back into the class definition in the header. Ugly, but it'll work.
Some compilers do cross-compilation unit template instantiation, but as you've discovered, g++ isn't one of them. (At least, not as it's configured on my system.)
Edit: As #juanchopanza pointed out above, this thread gives a good explanation of what's going on: Why can templates only be implemented in the header file?
I wrote a class named UserScore:
//header
using namespace std;
class UserScore{
public:
UserScore(const int &user_id, const int &rating);
private:
int _user_id;
int _rating;
};
//cpp
#include "UserScore.h"
UserScore::UserScore (const int &user_id, const int &rating):
_user_id(user_id),
_rating(rating)
{
}
The compile command is:
g++ src/UserScore.cpp -o obj/UserScore.o
But why this simple thing won't compile?
The error is:
Undefined symbols for architecture x86_64:
"_main", referenced from:
start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
You need to include the -c option to the compilation line if you want to generate an object file, otherwise the compiler assumes you are trying to build an executable and will complain if you don't have a main() method (which is happening here).
To make an object file which you will link later to a code file that has a "main()" method in it you need to use
g++ -c src/UserScore.cpp -o obj/UserScore.o
Which is what I think you are trying to do.
Alternatively you just need to add a main function to your code and then you can make an executable.
//header
using namespace std;
class UserScore{
public:
UserScore(const int &user_id, const int &rating);
private:
int _user_id;
int _rating;
};
//cpp
#include "UserScore.h"
UserScore::UserScore (const int &user_id, const int &rating):
_user_id(user_id),
_rating(rating)
{
}
int main()
{
return 0;
}
please consider these files:
p.h:
#ifndef _p_h_
#define _p_h_
class p{
public:
static void set_func(int(*)());
private:
static int (*sf)();
};
#endif
p.cpp:
#include "p.h"
#include <cstdio>
int (p::*sf)() = NULL; //defining the function pointer
void p::set_func(int(*f)()){
sf = f;
}
main.cpp:
#include "p.h"
#include <iostream>
int function_x(){
std::cout << "I'm function_x()" << std::endl;
return 1234;
}
int main(){
p::set_func(function_x);
}
when compiling, I get this:
$ g++ -o pp main.cpp p.cpp
/tmp/ccIs0M7r.o:p.cpp:(.text+0x7): undefined reference to `p::sf'
collect2: ld returned 1 exit status
but:
$ g++ -c -o pp p.cpp
compiles right.
What's wrong with the code? I just can't find where the problem is, please your help will be more than appreciated.
Thanks.
Your attempt at defining p::sf is incorrect – yours is a definition of a global variable named sf that is of type int (p::*)(), i.e. a pointer to a member function. Consequently p::sf remains undefined, hence the linker error.
Try this instead:
int (*p::sf)() = 0;
// or,
typedef int (*p_sf_t)();
p_sf_t p::sf = 0;
The difference is because error only occurs when you actually link the program. The problem is in your declaration of the static function pointer. The correct syntax is:
int (*p::sf)() = NULL; //defining the function pointer
You define a member function pointer and not a function pointer. I'm not sure what the correct syntax is, but I would have tried something like this:
int (*p::sf)() = NULL;
I will not give another answer (ildjarn answer is correct) but i will suggest you another way of achieving the same without static initialization (and the burdens it implies)
class p{
public:
typedef int (*func_t)();
static void set_func(func_t v) {
func_t& f = getFuncRef();
f = v;
}
static void call_func() {
func_t& f = getFuncRef();
assert( f != 0);
f();
}
private:
static func_t& getFuncRef() {
static func_t sf = 0;
return sf;
}
};
in this way you delegate the static initialization to a static function variable, which doesn't have the initialization order problems that affect static data variables, and is lazy-initialised