[완료]c++ 여러개의 파일을 컴파일 어떻게 하나요?

OpenSnake의 이미지

이거 쉬운거라서 검색하면 금방 나올거라고 생각했지만..이외로 안나오네요..-_-;

리눅스에서 C++ 파일을 여러개로 나눈 다음에 그 파일을 컴파일할라고 합니다.
어떻게 해야하나요?

#include <iostream>
 
class myclass{
  int i;
  public:
    void foo(int a);
};
 
int func(int a)
{
  return a;
}
 
void myclass::foo(int a)
{
  i = func(a);
  std::cout<<i<<"\n";
}
 
int main()
{
  class myclass ob1;
 
  ob1.foo(1);
 
  return 0;
}

위와 같은 파일을 여러개로 나눌라고 합니다.
foo.cpp main.cpp 이렇게 나눌라고 하는데요 어떻게 해야하나요??

C++을 사용을 별로 못해봤습니다...

chadr의 이미지

c/c++의 컴파일 단위는 소스파일 단위입니다.

그리고 추후에 링크 하는 과정을 거치게 됩니다.

그렇기 때문에 한개의 소스파일에서 include등을 해서 문법상 오류가 없게 나누시면 됩니다.
여기서 문법 오류라는 것은 키워드의 사용법은 물론이고 사용자 정의 타입(구조체, 클래스, 변수, 함수 등)의
선언들이 전부 모호함이 없이 정의 되어 있어야합니다.
-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

sDH8988L의 이미지

기본적으로 소스 파일을 나누는 기준은 해당 클래스 맴버 함수들의 정의를 한 파일에 넣고 나머지 main 함수 외 잡다한 것들을 또 다른 파일들에 넣습니다...

그리고 각각의 파일들을 컴파일 합니다. 이때, 각각의 파일들이 실행파일을 만드는 것이 아니고 .o 파일, 즉 오브젝트 파일을 만듭니다...

> g++ -c foo.cpp

를 하면, foo.o 라는 오브젝트 파일이 만들어질겁니다...

그 후에 main.cpp를 컴파일 하면 되죠... 이때는 -o 옵션을 줘서 실행 파일을 만듭니다. 또 좀 전에 만들어 둔 오브젝트 파일을 옵션으로 넣어 주면 되는 겁니다...

> g++ -o exe_name main.cpp foo.o

이렇게요...

물론, 파일 수가 많고 컴파일 구성이 복잡하다면, make 파일을 만들어 두는 것이 좋습니다...

make에 대한 tutorial은 웹에서 쉽게 구하실 수 있습니다...

OpenSnake의 이미지

main.cpp

#include <iostream>
 
int func(int a)
{
  return a;
}   
 
void myclass::foo(int a)
{
  i = func(a);
  std::cout<<i<<"\n";
}
 
int main()
{
  class myclass ob1;
 
  ob1.foo(1);
 
  return 0;
}

myclass.cpp
class myclass{
  int i;
  public:
  void foo(int a);
};

이렇게 컴파일 하니깐
$ g++ -o main main.cpp myclass.o
main.cpp:8: error: ‘myclass’ has not been declared
main.cpp: In function ‘void foo(int)’:
main.cpp:10: error: ‘i’ was not declared in this scope
main.cpp: In function ‘int main()’:
main.cpp:16: error: aggregate ‘myclass ob1’ has incomplete type and cannot be defined

이렇게 오류가 나오네요...
void myclass::foo(int a) 이게 클래스함수인가요?? 이게 여러개 있을때 파일도 이걸 여러개 만들수는 없나요?

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

sDH8988L의 이미지

한 3개 정도의 파일로 나눌 수 있겠네요...

1. foo.h : 이 파일에는 class definition과 간단한 function에 대한 declaration & definition이 들어갑니다...

#include &lt;iostream&gt;
 
class myclass
{
  int i;
  public:
    void foo(int a);
};
 
int func(int a) {   return a;  }

2. foo.cpp : 이 파일에는 myclass의 function definition이 들어갑니다...

#include "foo.h"
 
void myclass::foo(int a)
{
  i = func(a);
  std::cout<<i<<"\n";
}

3. main.cpp : 이 파일에는 main 함수가 들어갑니다...

#include "foo.h"
 
int main()
{
  myclass ob1;
 
  ob1.foo(1);
 
  return 0;
}

그 후에 컴파일은

> g++ -c foo.cpp
> g++ -o exec_name main.cpp foo.o

이렇게 하면 될 겁니다...

OpenSnake의 이미지

$ g++ -o main main.cpp foo.o
foo.o: In function `func(int)':
foo.cpp:(.text+0x0): multiple definition of `func(int)'
/tmp/ccOYhuAU.o:main.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status

혹시 h 헤더파일 경로설정같은것도 해야하나요?

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

sDH8988L의 이미지

ㅎㅎㅎ

이런... 이리 간단한 소스에서도 이런 문제가 생겼네요...

말씀대로 foo.h가 여러 곳에서 쓰여 func()가 중복 정의되어서 그렇습니다... 제가 부주의했네요...

이렇게 하시면 됩니다...

foo.h 파일에서 int func ... 라인을 선언만 합니다...

int func (int a);

이렇게요...

실제 정의는 foo.cpp 파일에서 하시면 됩니다...

int func (int a) { return a; }

이렇게요...

OpenSnake의 이미지

해결되었습니다.

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

--------------------------------------------
혼자있고 싶습니다. 모두 지구밖으로 나가주세요.

helloneo의 이미지

foo.h 를 여러군데서 include해서 func() 함수가 똑같은게 여러개 생겨서 그렇습니다..

foo.h 에있는 int func() 함수를 foo.cpp로 옮기고..
foo.h에는 다음줄을 추가하시면 될거것같습니다..

extern int foo(int a);

WHAT'S UP

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.