【问题标题】:Why I cannot run this simple c++ code by using g++ on mac?为什么我不能在 mac 上使用 g++ 运行这个简单的 c++ 代码?
【发布时间】:2015-04-12 07:38:28
【问题描述】:

我现在正在学习 C++,我正在尝试学习如何使用头文件。但是运行程序总是报错。

/* File add.h */
#ifndef ADD_H
#define ADD_H

int add(int, int);

#endif
/* ADD_H */


/* File add.cpp */
#include "add.h"

int add(int a, int b)
{
    return a + b;
}

/* File triple.cpp */
#include<iostream>
#include "add.h"
using namespace std;

int triple(int);
int triple(int x)
{
    return add(x, add(x, x));
}

int main()
{
  int i=0;
  int j;
  while (i<=5)
  {     j=triple(i);
        cout<<j<<endl;
       //cout<<triple(j)<<endl;
      i++;
   }
 return 0;
}

这是我使用的 3 个文件。当我运行时:g++ Triple.cpp 在mac上,错误如下:

Undefined symbols for architecture x86_64:
 "add(int, int)", referenced from:
   triple(int) in triple-e0558f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

谁能给我一些关于这个错误的提示。非常感谢! 顺便说一下,gcc 版本信息如下:

gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.51) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

【问题讨论】:

  • g++ add.cpp Triple.cpp -o out

标签: c++ gcc head


【解决方案1】:

两种编译方式:

一个。逐一编译

g++ -c add.cpp     -o add.o
g++ -c triple.cpp  -o triple.o
g++ add.o triple.o -o triple

b.一次编译所有内容

g++ add.cpp triple.cpp -o triple

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多