Hi, I'm working through the 3rd chapter of Thinking in C++ Vol 1 by Bruce Eckel (free online). I am using Code::Blocks as my IDE. I've try searching for this problem through the forum but haven't found a solution; I think it might be a IDE-specific problem.

The undefined reference error pops up when I try to compile Bitwise.cpp, which references printBinary.h which uses a function in printBinary.cpp. All 3 files are located in the same directory (in a folder called "C++" in My Documents).

The error message says "undefined reference to 'printBinary(unsigned char)'

For your convenience, I have pasted the code below:

//: C03:printBinary.h
// Display a byte in binary
void printBinary(const unsigned char val);
//: C03:printBinary.cpp {O}
#include <iostream>
void printBinary(const unsigned char val) {
  for(int i = 7; i >= 0; i--)
    if(val & (1 << i))
      std::cout << "1";
      std::cout << "0";
} ///:~
//: C03:Bitwise.cpp
//{L} printBinary
// Demonstration of bit manipulation
#include "printBinary.h"
#include <iostream>
using namespace std;

// A macro to save typing:
#define PR(STR, EXPR) \
  cout << STR; printBinary(EXPR); cout << endl;  

int main() {
  unsigned int getval;
  unsigned char a, b;
  cout << "Enter a number between 0 and 255: ";
  cin >> getval; a = getval;
  PR("a in binary: ", a);
  cout << "Enter a number between 0 and 255: ";
  cin >> getval; b = getval;
  PR("b in binary: ", b);
  PR("a | b = ", a | b);
  PR("a & b = ", a & b);
  PR("a ^ b = ", a ^ b);
  PR("~a = ", ~a);
  PR("~b = ", ~b);
  // An interesting bit pattern:
  unsigned char c = 0x5A; 
  PR("c in binary: ", c);
  a |= c;
  PR("a |= c; a = ", a);
  b &= c;
  PR("b &= c; b = ", b);
  b ^= a;
  PR("b ^= a; b = ", b);
} ///:~

Any help greatly appreciated =D

Recommended Answers

All 4 Replies

Must be a problem the way you created the project because I added all three files to a project in Code::Blocks and it compiled without error. Also worked with VC++ 2008 Express.

Did you create a project and add all the files to the project? The reason I ask is that if you don't you will get that error even if all the files are in the same directory.

Okay it works now, thanks for the help! Creating an empty project and adding the 3 files solved the problem =D

Or you can add #include "printBinary.cpp" into Bitwise.cpp.
I am beginner and might be wrong but works for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.