
linuxでリンクを貼るには
linuxでリンクを貼るには
本に書いてある通りにプログラムをつくったのですが、
うまくコンパイルできません。
本で書いてあるのはwindowsのvisual C++で、
僕の使っている環境はlinuxのg++です。
コンパイルした結果を以下に示します。
--
ファイル名:myfunc.h
//declaration of the max function
int max(int x, int y);
--
ファイル名:myfunc.cpp
//a definition of the max function
int max(int x, int y)
{
if(x > y)
return x;
else
return y;
}
--
ファイル名:sample10.5.cpp
#include <iostream>
#include "myfunc.h"
using namespace std;
int main()
{
int num1, num2, ans;
cout << "Please input the 1st integer.\n";
cin >> num1;
cout << "Please input the 2nd integer.\n";
cin >> num2;
ans = max(num1, num2);
cout << "The maximum value is " << ans << '\n';
return 0;
}
--
bash-2.05b$ g++ myfunc.cpp
/usr/lib/gcc-lib/i386-redhat-linux/3.2.3/../../../crt1.o(.text+0x18): In function `_start':
: undefined reference to `main'
collect2: ld はステータス 1 で終了しました
--
bash-2.05b$ g++ sample10.5.cpp
/tmp/ccWJNOkX.o(.text+0x6c): In function `main':
: undefined reference to `max(int, int)'
collect2: ld はステータス 1 で終了しました
投稿日時 - 2010-09-08 18:20:45
Visual Cとかだと、IDE側でまとめてやってくれるので、そういう説明が無いこともあるでしょうね。
方法は2つ。
1) g++ sample10.5.cpp myfunc.cpp
と続けて書く
2)
g++ -c sample10.5.cpp
g++ -c myfunc.cpp
と -c オプションを付けてオブジェクトファイルにコンパイルする(拡張子 .o )
→
g++ sample10.5.o myfunc.o
でリンク
数が少ないときは1)でよいですが、大規模になってくると、更新した分だけコンパイルすればよい 2)の方法がいいです。
依存関係をMakefileに書いておけば、 make コマンド一つで更新されたものだけコンパイルしてくれます。
投稿日時 - 2010-09-08 19:17:31
ご回答頂きありがとうございます。
2つの方法があるのですね。
とても参考になりました。
投稿日時 - 2010-09-08 20:33:22
このQ&Aは役に立ちましたか?
2人が「このQ&Aが役に立った」と投票しています
回答(3)
g++ sample10.5.cpp myfunc.cpp
とするか、コンパイルとリンクを分けて、
g++ -c sample10.5.cpp
g++ -c myfunc.cpp
g++ sample10.5.o myfunc.o
の3コマンドを実行することも可能。
こうすると変更していないファイルのコンパイルが要らないので時間短縮になります。
さらに、make というコマンドを使えば、このあたりの処理を自動化できます。
(VisualStudio は、単なるコンパイラではなく、make 相当の機能も持っています)
投稿日時 - 2010-09-08 19:13:51
ご回答頂きありがとうございます。
無事処理ができました。
makeということも勉強してみます。
投稿日時 - 2010-09-08 20:32:37