2

Assignment says: Write a program that consists of two source-files. The first (Main.c) contains the main() function and gives the variable i a value. The second source-file (Print.c) multiplies i by 2 and prints it. Print.c contains the function print() which can be called from main().

In my attempt to do this assignment, I created three files: main.cpp

#include <stdio.h>
#include "print.h"
using namespace std;

// Ex 1-5-3

// Global variable
int i = 2;


int main() {
    print(i);

    return 0;
}

print.cpp:

#include <stdio.h>
#include "print.h"
using namespace std;

// Ex 1-5-3

// Fetch global variable from main.cpp
extern int i;

void print(int i) {
    printf("%d", 2*i);
}

print.h:

#ifndef GLOBAL_H // head guards
#define GLOBAL_H

void print(int i);

#endif

I compiled print.cpp and when I tried to compile and run main.cpp, it says: [Linker error] undefined reference to 'print(int)'

Why isn't it accepting my definition of void print (int i) in print.cpp and referring to it through the header print.h? Thanks!

2
  • 1
    How are you linking? It could be as simple as forgetting to link in print.o. Commented Oct 12, 2012 at 3:07
  • 1
    You don't need the extern since i is a parameter. Commented Oct 12, 2012 at 3:25

1 Answer 1

2

Not sure what compiler you're using, but I got it to work on Linux/gcc:

$ gcc main.cpp print.cpp -o test
$ ./test 
$ 4 
$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.