2012-10-12 73 views
1

賦值說:寫一個由兩個源文件組成的程序。第一個(Main.c)包含main()函數並給變量i一個值。第二個源文件(Print.c)將i乘以2並打印出來。 Print.c包含可以從main()調用的print()函數。未定義引用'print(int)'[鏈接器錯誤]

在我試圖做這個任務,我創建了三個文件: 的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 

我編譯print.cpp,當我試圖編譯和運行main.cpp時,它說: [L inker error] undefined reference to'print(int)'

爲什麼它不接受我在print.cpp中定義的void print(int i),並通過頭文件print.h引用它?謝謝!

+1

如何鏈接?這可能就像忘記在print.o中鏈接一樣簡單。 –

+1

你不需要'extern',因爲'i'是一個參數。 –

+0

感謝幫助! – JZL

回答

2

不知道你正在使用的編譯器,但我得到了它在Linux/gcc的工作:

$ gcc main.cpp print.cpp -o test 
$ ./test 
$ 4 
$ 
相關問題