Click here to Skip to main content
15,918,889 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I include the header file, it says cannot find the function definition,
but when I include the cpp file, it works,
why...

in A.h
C++
#ifndef A_H
#define A_H

#include <stdlib.h>

class A{
  int member1;
 public:
  void Assign(int v);
  void Print();
};

#endif


in A.cpp
C++
#include "A.h"
#include <iostream>

using namespace std;

void A::Assign(int v){
  member1 = v;
}
void A::Print(){
  cout<<member1<<endl;
}


in main.cpp
C++
#include <stdlib.h>
#include "A.h";

int main(){
  A a1;
  a1.Assign(1);
  a1.Print();
  return 0;



error:
in main.cpp: undefined ref to A::Assign...

Thanks
Posted
Updated 21-Feb-13 20:14pm
v2

All correct. Well, included <stdlib.h> it totally redundant. You should not have this error. Maybe the files are actually different, or some files are not actually included in project, or something. The files themselves are correct. Well, try to recreate the project from scratch (with such files, don't use precompiled headers) accurately, with the same exact content; it will work.

—SA
 
Share this answer
 
Comments
zhaoyilong1 22-Feb-13 2:14am    
it can actually find the function, but says theres no definition of it~...
Sergey Alexandrovich Kryukov 22-Feb-13 11:29am    
You do have the definition. This is tiny code, and the problem can be only in project structure/options. It compiles if you do it right. Start over, make sure you understand each step; and use the code you already have. Ask a question is you don't understand some steps...
—SA
In Main.cpp, try using #include "A.h", not #include <A.h>.
Cheers
Andi
 
Share this answer
 
Comments
zhaoyilong1 22-Feb-13 2:12am    
oh. that's a typo. I did the right thing there, but it is not working ~ However when I include A.cpp rather than A.h, it all works...... it makes no sense to me now.
Have you included A.cpp in you project. Looks like the linker is complaining that it doesn't find the definition of A::Assign.

You should give us the exact error message that you are receiving. That could show if my assumption is true.
 
Share this answer
 
Comments
enhzflep 22-Feb-13 2:22am    
exactly! That's where "undefined reference" comes from - the linker.
zhaoyilong1 22-Feb-13 2:43am    
yea ~ I forgot to include a.cpp into makefile
How are you compiling your project?
If you're using an IDE, did you ensure that A.cpp is added to the project?
If you're compiling from the command line or a makefile, did you ensure you added both main.cpp and A.cpp as dependencies for the output executable?
 
Share this answer
 
v2
Comments
zhaoyilong1 22-Feb-13 2:42am    
yeayea ,,,, I forgot to compile a.cpp in my makefile ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900