我制作了一個非常簡單的 C 程式,其目標是在不同的檔案中使用函式。該函式只是列印出在引數中傳遞的某個訊息。經過一番研究,我讀到對于這樣的專案,我需要 3 個檔案:主檔案、頭檔案和函式(顯然我不應該將函式代碼放在頭檔案中。)我現在有三個檔案:
- main.cpp(主檔案)
- simple.h(頭檔案(函式定義))
- simple.cpp(函式檔案)
每當我試圖讓它們一起作業時,我總是會遇到同樣的錯誤:
C:\Users\juuhu\AppData\Local\Temp\ccQRa0R0.o:main.cpp:(.text 0x43): undefined reference to `message(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2.exe: error: ld returned 1 exit status
這是三個檔案的代碼:
主檔案
#include <iostream>
#include "simple.h"
using namespace std;
int main(){
message("Hello world!");
return 0;
}
簡單的.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include <string>
void message(std::string message);
#endif
簡單的.cpp
#include "simple.h"
void message(std::string message){
cout << message;
}
uj5u.com熱心網友回復:
我使用 Visual Studio 2019 編譯您的代碼。首先編譯錯誤輸出:“Error C2065 'cout': undeclared identifier message”。
當我添加#include<iostream>simple.h 并將 simple.cpp 訊息函式更改cout為 時std::cout,程式輸出“Hello world!”
- 簡單的.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include<iostream>
#include <string>
void message(std::string message);
#endif
- 簡單的.cpp
#include "simple.h"
void message(std::string message) {
std::cout << message;
}
你可以再試一次,希望你成功編譯代碼并得到你想要的。
uj5u.com熱心網友回復:
您尚未將函式定義檔案鏈接到頭檔案。
簡單的.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include <string>
#include "simple.cpp" // include the simple.cpp file
void message(std::string message);
#endif
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418835.html
標籤:
上一篇:Rust中不同功能的意義何在?
