C/C++ full file path in assert macro - c++

I am wondering if it's possible to display full file path using the assert macro?
I cannot specify full file path in compilation command, is there still a way to do it?
My debug environment is linux/g++

You can add the following macro option into your compilation line (Can be easily modify for your environment)
%.o: %.cpp
$(CC) $(CFLAGS) -D__ABSFILE__='"$(realpath $<)"' -c $< -o $#
then you just have to this to have your full path:
#include <stdio.h>
int main()
{
printf(__ABSFILE__);
// will be expanded as: printf("/tmp/foo.c")
}
EDIT
Even better than this: The following rules is enough !!!
%.o: %.cpp
$(CC) $(CFLAGS) -c $(realpath $<) -o $#
And you can now use __FILE__ macro:
#include <stdio.h>
int main()
{
printf(__FILE__);
// will be expanded as: printf("/tmp/foo.c")
}

assert uses the __FILE__ macro to get the filename. It will expand to the path used during compilation. For example, using this program:
#include <stdio.h>
int main(void)
{
printf("%s\n", __FILE__);
return 0;
}
If I compile with 'gcc -o foo foo.c' and run, I'll get this output:
foo.c
But if I compile with 'gcc -o foo /tmp/foo.c' and run, I'll get this output instead:
/tmp/foo.c

Related

How to create Makefile for multiple files in multiple directories?

Good morning,
I new in c++ and I am trying to compile my simple code to executable form. I will explain structure of project.
- main.cpp
- /utility/server.h
- /utility/server.cpp
I enclose file sources for complete information.
main.cpp
#include <iostream>
#include "utility/server.h"
using namespace std;
using namespace server;
int main() {
std::cout << "Content-type:text/html\r\n\r\n";
std::cout << "Your server name is: " << server::get_domain() << '\n';
return 0;
}
server.cpp
#include <cstdlib>
#include "server.h"
namespace server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
}
To my Makefile I added comments to understand what I want to do.
#
# 'make' build executable file
# 'make clean' removes all .o and executable files
#
# define the C compiler to use
CC = g++
# define any compile-time flags
CFLAGS = -Wall -g
# define any directories containing header files other than /usr/include
INCLUDES = -I../utility
# define the C++ source files
SRCS = main.cpp utility/server.cpp
# define the C++ object files
OBJS = $(SRCS:.cpp=.o)
# define the executable file
MAIN = executable.cgi
#
# The following part of the makefile is generic
#
.PHONY: depend clean
all: $(MAIN)
$(MAIN): $(OBJS)
$(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS)
# this is a suffix replacement rule for building .o's from .cpp's
.c.o:
$(CC) $(CFLAGS) $(INCLUDES) -cpp $< -o $#
clean:
$(RM) *.o *~ $(MAIN)
depend: $(SRCS)
makedepend $(INCLUDES) $^
And finally error from compilation
g++ -Wall -g -I../utility -o executable.cgi main.o utility/server.o
Undefined symbols for architecture x86_64:
"server::get_domain()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [executable.cgi] Error 1
From error message I understood there is problem with utility folder, but I don't know how to fix it.
Thank you for your help :)
In server.cpp, here:
namespace server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
}
You have made char* server::get_domain() a static function, making
its definition visible only within this translation unit and invisible to
the linker. Remove the keyword static here, and also in server.h if you have declared the function static there.
A namespace is not a class or struct. Confusingly,
namespace server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
}
server::get_domain() is a static function in that namespace. But
struct server {
static char* get_domain() {
return getenv("SERVER_NAME");
}
};
it is a global function in that class, which the linker can see.

Undefined reference when compiling a C and C++ file with same header

To make this short, I have a CPP and C code, and my CPP code is trying to reference functions from the C code with a header file. Whenever I run the make command, I end up getting "undefined reference" errors. Here are my codes:
cpp_code.cpp:
extern "C"{
#include "header_code.h";
}
int main(){
cout << "Hello" << endl;
return 0;
}
c_code.c:
#include "header_code.h"
int main(){
printf("Hello");
return 0;
}
void initalize(){
printf("Initilized");
}
header_code.h:
extern void initalize();
makefile:
CXX = g++
CXXFLAGS = -std=c++11
CC = gcc
DEPS = header_code.h
CFLAGS = -I
OBJS = cpp_code.o c_code.o
c: $(OBJS)
$(CXX) -o $# $^ $(CXXFLAGS)
%.o : %.cpp
$(CXX) -c $(CXXFLAGS) $<
%.o : %.c $(DEPS)
$(CC) -c $(CFLAGS) $<
Whenever running make it always gives me problems. Can anyone please help me? Thank you for your time reading all of this!
[basic.start.main]
A program that declares a variable main at global scope, or that declares a function main at global scope attached to a named module, or that declares the name main with C language linkage (in any namespace) is ill-formed.
So, as a C++ program, it's ill-formed. Remove the C main function.
Other problems:
In the makefile you have
CFLAGS = -I
and whatever comes after that when compiling will be treated as a directory to search for header files in. In your makefile, that's the source file. Correction:
CFLAGS =
or
CFLAGS = -I.
Your header file is missing a header guard and header files that are supposed to be used by both C and C++ code usually contain the extern "C" part themselves to not burden C++ users to add it.
cpp_code.cpp
#include "header_code.h"
#include <iostream>
int main() {
initalize(); // call the C function
std::cout << "Hello" << std::endl;
}
c_code.c
#include "header_code.h"
#include <stdio.h>
void initalize(){
printf("Initilized");
}
header_code.h
#ifndef HEADER_CODE_H_
#define HEADER_CODE_H_
#ifdef __cplusplus
extern "C" {
#endif
extern void initalize();
#ifdef __cplusplus
}
#endif
#endif
makefile
CXX = g++
CXXFLAGS = -std=c++11
CC = gcc
DEPS = header_code.h
CFLAGS = -I.
OBJS = cpp_code.o c_code.o
c: $(OBJS)
$(CXX) -o $# $^ $(CXXFLAGS)
%.o : %.cpp
$(CXX) -c $(CXXFLAGS) $<
%.o : %.c $(DEPS)
$(CC) -c $(CFLAGS) $<

C++ How would I combine two makefile object target rules (which are located in another folder) into one target/rule?

My C++ program consists of three files:
two source files 'main.cpp' and 'hellolib.cpp'
a header file 'hellolib.h'
I am creating a makefile for this program. For my assignment I need one target ('hello') that compiles all source files in an executable.
Another target ('obj') should compile all '.cpp' files into objects and link them together in an executable.
When running make I prefer the object files to be created in a seperate folder called 'bin'. The source files are would be in a folder called 'src'. These folders are siblings, the makefile is in it's parent folder.
My makefile works fine but I wish two combine the two targets 'bin/main.o' and 'bin/hellolib.o' into one to reduce the amount of rules, especially for later when I am dealing with more source files.
I imagined the replacement would look something like this, but it doesn't seem to work.
It gives me the error: "*** No rule ot make target 'bin/main.o',
needed by 'obj'. Stop.
bin/%.o : src/%.cpp
$(CC) -c $< -o $#
Working Makefile:
CC = g++
SOURCES = ./src/main.cpp \
./src/hellolib.cpp
OBJECTS = ./bin/main.o \
./bin/hellolib.o
hello : $(SOURCES)
$(CC) -o $# $^
obj : $(OBJECTS)
$(CC) -o $# $^
bin/main.o : src/main.cpp
$(CC) -c $< -o $#
bin/hellolib.o : src/hellolib.cpp
$(CC) -c $< -o $#
clean:
#rm -rf hello obj bin/*.o
main.cpp:
#include "hellolib.h"
int main() {
Hello h("Name");
h.Print();
return 0;
}
hellolib.cpp
#include "hellolib.h"
#include <iostream>
Hello::Hello(std::string name) {
if (name.empty()) {
cout << "Name is not valid!";
return;
}
_name = name;
}
void Hello::Print() {
cout << "Hello " << _name << endl;
}
hellolib.h
#ifndef HELLO_LIB_H
#define HELLO_LIB_H
#include <string>
using namespace std;
class Hello {
std::string _name;
public:
Hello(std::string name);
void Print();
};
#endif
You need to change:
OBJECTS = ./bin/main.o \
./bin/hellolib.o
to:
OBJECTS = bin/main.o \
bin/hellolib.o
(Removing leading "./"). Either that, or change your pattern rule to include the leading "./":
./bin/%.o : src/%.cpp
$(CC) -c $< -o $#
Make rule matching uses text matching. It's not based on filenames, so "./././foo" and "foo" are not the same thing.
Personally I recommend rewriting like this:
SOURCES = src/main.cpp \
src/hellolib.cpp
OBJECTS = $(patsubst src/%.cpp,bin/%.o,$(SOURCES))
so you only need to keep the list of files in one place.
You can make a rule that builds anything conforming to a specific pattern like this:
bin/%.o : src/%.cpp
$(CC) -c -o $# $<
That will compile any bin/%.o dependency from the corresponding source src/%.cpp.
Also it is standard when compiling C++ to use CXX rather than CC (which is for C code).

Static methods declared but not defined error c++

I have a static method in class as follows in file Convert.h
class Convert
{
public :
static string convertIntToStr(unsigned int integer);
};
In Convert.cpp
string
Convert::convertIntToStr(unsigned int integer)
{
ostringstream ostr;
ostr << integer;
return ostr.str();
}
I use this in some other class method in another .cpp file as Convert::convertIntToStr, but I get linking error, which says undefined reference to Convert::convertIntToStr(unsigned int). Could you please let me know what could be wrong?
With multiple cpp file, you have to link the compiled object file into executable. In IDE like eclipse CDT or Visual stdio, It has been done for you.
To compile and link by yourself, with gcc for example, write Makefile:
CC=g++
CPPFLAGS=-fPIC -Wall -g -O2
all:executable
executable: convert.o other.o
$(CC) $(CPPFLAGS) -o $# $^
convert.o: convert.cpp
$(RC) $^
other.o: other.cpp
$(CC) -o $# -c $^
.PHONY:clean
clean:
rm *.o executable

Replacing symbol from object file at compile time. For example swapping out main

Here's the use case:
I have a .cpp file which has functions implemented in it. For sake of example say it has the following:
[main.cpp]
#include <iostream>
int foo(int);
int foo(int a) {
return a * a;
}
int main() {
for (int i = 0; i < 5; i += 1) {
std::cout << foo(i) << std::endl;
}
return 0;
}
I want to perform some amount of automated testing on the function foo in this file but would need to replace out the main() function to do my testing. Preferably I'd like to have a separate file like this that I could link in over top of that one:
[mymain.cpp]
#include <iostream>
#include <cassert>
extern int foo(int);
int main() {
assert(foo(1) == 1);
assert(foo(2) == 4);
assert(foo(0) == 0);
assert(foo(-2) == 4);
return 0;
}
I'd like (if at all possible) to avoid changing the original .cpp file in order to do this -- though this would be my approach if this is not possible:
do a replace for "(\s)main\s*\(" ==> "\1__oldmain\("
compile as usual.
The environment I am targeting is a linux environment with g++.
I hate answering my own question, but here's a solution I ended up finding deep in the man page of g++, I've tested it and it works to what I would want it to...
g++ has the -D flag which allows you to define macros when compiling object files. I know you are thinking "ugh macros" but hear me out... You can use the macro definition to effectively rename a symbol. In my case, I can run the following command to generate an object file of my students code without their main file: g++ -D main=__students_main__ main.cpp -c -o main.nomain.o.
This creates an object file with their int main defined as int __students_main__. Now this isn't necessarily callable directly as they could have defined main as int main(void) or with the various combinations of argc and argv, but it allows me to effectively compile out their function.
The final compile looks like this:
g++ -c -D main=__students_main__ main.cpp -o main.nomain.o
g++ -c mymain.cpp -o mymain.o
g++ main.nomain.o mymain.o -o mymainstudentsfoo.out
For my purposes, I wanted to create a Makefile that would accomplish this automagically (ish) and I feel that is relevant to this discussion so I'll post what I came up with:
HDIR=./ # Not relevant to question, but we have headers in a separate directory
CC=g++
CFLAGS=-I $(HDIR)
NOMAIN=-D main=__student_main__ # The main renaming magic
.SECONDARY: # I forget exactly what this does, I seem to remember it is a hack to prevent deletion of .o files
cpp = $(wildcard *.cpp)
obj = $(patsubst %.cpp,%.o,$(cpp))
objnomain = $(patsubst %.cpp,%.nomain.o,$(cpp))
all: $(obj) $(objnomain)
clean:
rm -f *.o *.out
%.nomain.o: %.cpp
$(CC) $(CFLAGS) $(NOMAIN) -c $^ -o $#
%.o: %.cpp
$(CC) $(CFLAGS) -c $^
You can use the --allow-multiple-definition option of ld*:
[a.c]
#include <stdio.h>
int foo() { return 3; }
int bar() { return 4; }
int main(void)
{
printf("foo: %i\n", foo());
return 0;
}
[b.c]
#include <stdio.h>
int bar();
int main(void)
{
printf("bar: %i\n", bar());
return 0;
}
[shell]
$ gcc -Wall -c a.c
$ gcc -Wall -c b.c
$ gcc -Wl,--allow-multiple-definition a.o b.o -o foobar && foobar
foo: 3
$ gcc -Wl,--allow-multiple-definition b.o a.o -o foobar && foobar
bar: 4
*: At your own risk :)
I support 'djechlin's suggestion.
But if you want something quick and dirty, here's a suggestion:
You can define a macro and wrap your function calls like this,
#ifdef MYTESTING
#define ASSERTEQUAL(fn, parm, ret) \
assert( fn ( parm ) == ret )
#else
#define ASSERTEQUAL(fn, parm, ret) fn ( parm )
#endif
And in your main function use the following call,
ASSERTEQUAL( foo, i, 4);
Use the following compilation flag to enable the customized macro behavior.
-DMYTESTING
Hope this helps!
It is not possible to do this at compile time. You need a link time solution. (Or to make use of the preprocessor.)
In either case, you'd probably want to separate the "regular" and "testing" symbols and selectively include their source files in compilation, or object files in linking.*
Though I'd rather use a unit testing framework or at least NDEBUG for assert()s.
*e.g.:
#ifdef TESTING
#include "main-testing.c"
#else
#include "main.c"
#endif
or
ifdef TESTING
OBJS += main-testing.o
else
OBJS += main.o
endif
Update: I just realized that you're specifically looking for a solution where main-testing.o's main would override main.o's (right?). I'll keep this answer and add another one for the "override" solution.