Hi, new to this so go easy.
I'm trying to store a function i wrote in a file and call it with a header file rather than copy and paste as ive been doing but i keep getting error messages from the compiler.
Can anyone point out what i'm doing wrong?

the header file is:

#ifndef GUARD_is_prime_h
#define GUARD_is_prime_h

bool is_prime(unsigned long long int);

#endif

this is saved as is_prime.h

is_prime.cpp is;

bool is_prime(unsigned long long int a)
{
     if(a==1){return false;}
     if(a<4){return true;}
     if(a%2==0){return false;}
     if(a<9){return true;}
     if(a%3==0){return false;}
     unsigned long long int i;
     for(i=5;(i*i)<=a;i+=6)
     {
                           if(a%i==0){return false;}
                           if(a%(i+2)==0){return false;}
     }
     return true;
}

i then tried to write a simple program that asks if a number is prime having used
#include "is_prime.h" and i get the following error

In function main
[Linker error]undefined reference to is_prime(unsigned long long)
Id returned 1 exit status

any help greatly appreciated.:)

Recommended Answers

All 9 Replies

this is the test program i wrote

#include <iostream>
#include "is_prime.h"

using namespace std;

int main()
{
    if(is_prime(50)){cout<<"yes"<<endl;}
    else{cout<<"no"<<endl;}
    
    
    system("pause");
    return 0;
}

you need to include is_prime.h in your is_prime.cpp file.

ok tried that and still getting same error message.

Can you post the 3 files exactly as you're using them?

don't understand thought i had.

The issue is most-likely that "is_prime.cpp" is not getting compiled as part of your compilation process.

What OS and IDE are you using?

Is the file "is_prime.cpp" included as part of your "project" in your IDE? If not, it doesn't get compiled and the linker can't find the object code that it needs to finish the job.

using dev on windows

the files are just saved in the directory

isn't a project (unsure what that means, have only been writing one off programs up to this point) just three seperate files.

No, projects are actually an organizational system within the IDE. You add files to a "project" then the IDE's project system automatically manages creation of the make file used during compilation for you. If you have more than 1 *.cpp file for the program you are working on, all of those files should be part of the "project".

Take a look at the "screenie" that I've attached. This particular one is for MS-VC++ 2008, but the concept is the same. Notice how I have added all 3 files to the project. If I remove "is_prime.cpp" from the project, it will cause the same linker error you are experiencing.

thanks. put it all in one project and it seems to work fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.