Access pre-compiled functions within a class C++/11 - c++

Sorry if the title is misleading, I'm currently looking for solutions to the following:
I'm developing a library, for other people to use. They have to follow a strict design concept and the way they structure any additional features within the library. They all use Linux and (Vim) and as such as are allowed to use terminal commands (i.e to be able to compile etc..) and we all use clang as a compiler.
My question is this: Let's suppose I write a function called: "checkCode":
template<typename T>
void checkCode(T&& codeSnippet)
{
//// code
}
I want to make this function run so whenever they type "checkCode" in a terminal this function is therefore called. I know using clang thy have similar functionality, however, this is understandable as you're using the whole of clang. So:
1) Is it possible to just compile a class, and then access each of the functions through
the .dylab | .so file?
2) Might it be a better idea, or, better to take a copy of the source of clang, add this functionality and role it out to those using and contributing to the library? This would be like an additional add-on to clang?
Thanks

you could use one executable and symbolic links to it like busybox:
int main(int argc, char **argv)
{
string programName = argv[0];
size_t lastSlash = programName.find_last_of('/');
if(lastSlash != string::npos)
programName = programName.substr(lastSlash + 1);
if(programName == "function_1")
{
function_1();
return 0;
}
if(programName == "function_2")
{
function_2();
return 0;
}
// ...
// normal main code
return 0;
}

Related

How can I combine many C++ main() functions into a single binary?

I'm working with a large C++ project that presently produces 66 different binaries. Each entrypoint contains its own global variables and main() function, though there's a lot of common code that's provided through a shared library.
For ease of distribution, I would like to distribute a single statically-linked binary, like you'd get from a Go or Rust project. Instead of invoking:
./ProgramFoo
./ProgramBar
I'd like to have a single combined binary that "execs" itself into one of those tools behind the scenes based on argv parameters, sort of like how busybox works:
./CombinedProgram ProgramFoo
./CombinedProgram ProgramBar
Look, I get that there's a "right" way to do this — refactor all 66 source files. Replace all global state with class singletons. Replace all the main() functions with entrypoint functions that could be dispatched from a single, unifying main() function. That sounds like a lot of work and a fair amount of disruption to all the other developers on the project. Is there truly no alternative on the compiler/linker level?
(I also don't want to just archive the binaries inside the CombinedProgram, write them to disk, and exec them. Boo. If I wanted a tarball, I'd just use a tarball.)
My understanding of C/C++ binary production is that the compiler will insert a crt0 startup routine that will initialize all my global state and then invoke main() with the appropriate parameters. Could I... perhaps... sneak some code in before that crt0 that peeks at argv and then proceeds down the correct code path?
Is there truly no alternative on the compiler/linker level?
Not really. Refactoring is the best / least work way to accomplish your task.
% cc -o one busy.c ; ln one two ; ./one ; ./two
one
two
The main() needs to look at ARGV[0] to determine how it was called. Then act on that information.
Simplest example:
#include <stdio.h>
#include <string.h>
int one(int argc, char **argv) {
printf("one\n");
return 1;
}
int two(int argc, char **argv) {
printf("two\n");
return 2;
}
int main(int argc, char **argv) {
char *end = argv[0];
int len = strlen(end);
end += len; // jump to the end of the command.
if (argc >= 1) {
if (!strcmp(end-3, "one")) {
return one(argc, argv);
} else if (!strcmp(end-3, "two")) {
return two(argc, argv);
}
}
}
I don't know of a tool that automatically refactors the commands into functions. The alternative is having one file determine what to do and then exec one of the 66 other statically-linked binaries.

function contains unnamed parameter

I'm a new programmer,my program is about getting LED on,maybe the simplest in C language,but it is always having _'Delay10ms':function contains unnamed parameter,hoping someone help me to solve it.
here are my words:
#include<reg51.h>
#include<intrins.h>
#define GPIO_LED P2
void Delay10ms(unsigned char time)
{
unsigned char i,j;
for(i=1;i<110*time;i++)
for(j=1;j<110;j++);
}
void main()
{
unsigned char n,i,j;
GPIO_LED=0X01;
while(1)
{
for(n=0;n<7;n++)
{
GPIO_LED=_crol_(GPIO_LED,1);
Delay10ms(50);
}
for(n=0;n<7;n++)
{
GPIO_LED=_cror_(GPIO_LED,1);
Delay10ms(50);
}
}
}
Either <reg51.h> or <intrins.h> probably have standard library includes. One of these library includes contains the standard header function time() that returns the current system time. Because your function parameter's name is time the IDE probably can't figure out what you meant with it and thus it gives you that error/warning. Try renaming your variable.
Also, the return type of main() has never been void (C++), use int.
It has been a Long time gone since I played c, but your code Looks o.k., maybe there is a name conflict ("time")
But there are some more questions:
- Why do you use char (unsigned char = 0..255) instead of classic int? This would be make code more readable.
- What do you expect how relyable your timer could be on a multitasking operating System?
I would implement such a function (if it not exists) as
void MyDelay (unsigned int delay_time)
{
start = MyOs.GiveMeTheTime()
while (MyOs.GiveMeTheTime() - start < delay_time)
{};
}
MyOs and GiveMeTheTime are names chosen by me. You must find out, which functions are available on your System, I am sure, they are.
I suppose, you try to program anything like a raspberry pi. Maybe this link could help:
Example Which Provides Accurate uS Timing

Getting a function name (__func__) from a class T and a pointer to member function void(T::*pmf)()

Is it possible to write some f() template function that takes a type T and a pointer to member function of signature void(T::*pmf)() as (template and/or function) arguments and returns a const char* that points to the member function's __func__ variable (or to the mangled function name)?
EDIT: I am asked to explain my use-case. I am trying to write a unit-test library (I know there is a Boost Test library for this purpose). And my aim is not to use any macros at all:
struct my_test_case : public unit_test::test {
void some_test()
{
assert_test(false, "test failed.");
}
};
My test suite runner will call my_test_case::some_test() and if its assertion fails, I want it log:
ASSERTION FAILED (&my_test_case::some_test()): test failed.
I can use <typeinfo> to get the name of the class but the pointer-to-member-function is just an offset, which gives no clue to the user about the test function being called.
It seems like what you are trying to achieve, is to get the name of the calling function in assert_test(). With gcc you can use
backtace to do that. Here is a naive example:
#include <iostream>
#include <execinfo.h>
#include <cxxabi.h>
namespace unit_test
{
struct test {};
}
std::string get_my_caller()
{
std::string caller("???");
void *bt[3]; // backtrace
char **bts; // backtrace symbols
size_t size = sizeof(bt)/sizeof(*bt);
int ret = -4;
/* get backtrace symbols */
size = backtrace(bt, size);
bts = backtrace_symbols(bt, size);
if (size >= 3) {
caller = bts[2];
/* demangle function name*/
char *name;
size_t pos = caller.find('(') + 1;
size_t len = caller.find('+') - pos;
name = abi::__cxa_demangle(caller.substr(pos, len).c_str(), NULL, NULL, &ret);
if (ret == 0)
caller = name;
free(name);
}
free(bts);
return caller;
}
void assert_test(bool expression, const std::string& message)
{
if (!expression)
std::cout << "ASSERTION FAILED " << get_my_caller() << ": " << message << std::endl;
}
struct my_test_case : public unit_test::test
{
void some_test()
{
assert_test(false, "test failed.");
}
};
int main()
{
my_test_case tc;
tc.some_test();
return 0;
}
Compiled with:
g++ -std=c++11 -rdynamic main.cpp -o main
Output:
ASSERTION FAILED my_test_case::some_test(): test failed.
Note: This is a gcc (linux, ...) solution, which might be difficult to port to other platforms!
TL;DR: It is not possible to do this in a reasonably portable way, other than using macros. Using debug symbols is really a hard solution, which will introduce a maintenance and architecture problem in the future, and a bad solution.
The names of functions, in any form, is not guaranteed to be stored in the binary [or anywhere else for that matter]. Static free functions certainly won't have to expose their name to the rest of the world, and there is no real need for virtual member functions to have their names exposed either (except when the vtable is formed in A.c and the member function is in B.c).
It is also entirely permissible for the linker to remove ALL names of functions and variables. Names MAY be used by shared libraries to find functions not present in the binary, but the "ordinal" way can avoid that too, if the system is using that method.
I can't see any other solution than making assert_test a macro - and this is actually a GOOD use-case of macros. [Well, you could of course pass __func__ as a an argument, but that's certainly NOT better than using macros in this limited case].
Something like:
#define assert_test(x, y) do_assert_test(x, y, __func__)
and then implment do_assert_test to do what your original assert_test would do [less the impossible bit of figuring out the name of the function].
If it's unit tests, and you can be sure that you will always do this with debug symbols, you could solve it in a very non-portable way by building with debug symbols and then using the debug interface to find the name of the function you are currently in. The reason I say it's non-portable is that the debug API for a given OS is not standard - Windows does it one way, Linux another, and I'm not sure how it works in MacOS - and to make matters worse, my quick search on the subject seems to indicate that reading debug symbols doesn't have an API as such - there is a debug API that allows you to inspect the current process and figure out where you are, what the registers contain, etc, but not to find out what the name of the function is. So that's definitely a harder solution than "convince whoever needs to be convinced that this is a valid use of a macro".

Mocking system calls - is there better way? [duplicate]

This question already has answers here:
Advice on Mocking System Calls
(6 answers)
Closed 9 years ago.
We are now introducing unit tests in our company and thinking about best way of mocking system calls.
Consider the following code
int fd = open(path, O_RDONLY);
if (fd < 0) {
LOG.error() << "cannot load plugin " << path << std::endl;
return ERROR(ERROR_OPENING_PLUGING);
}
// do other stuff
Obviously, we need to mock system call to open
I have found following ways to do so:
Correct - in the terms of design but ugly way. Create interface and impl
class ISystem
{
public:
typedef std::auto_ptr<ISystem> Ptr;
ISystem() {};
virtual ~ISystem() {};
virtual int open(const char* file, int path) = 0;
};
class System : public ISystem
{
public:
System() {};
virtual ~System() {};
virtual int open(const char* file, int path);
static ISystem::Ptr Get();
};
and use it
Common::Error dlopen_signed(ISystem::Ptr& system, const char* path, int flags, void*& ret)
{
int fd = system->open(path, O_RDONLY);
if (fd < 0) {
LOG.error() << "cannot load plugin " << path << std::endl;
return ERROR(ERROR_OPENING_PLUGING);
}
char fd_path[32];
I dont like it because every function will need to have one more argument - ISystem::Ptr& system, that will be the same for all production code.
Also, not sure about speed (this involves extra layers for basic system calls that must be really fast)
2) Use a link seam
Linker is designed so that it prefer your versions of functions than system ones.
But this does not work for some system calls, for example open (not sure about the reason), and this solution is a little bit hackish.
3) use --wrap compiler functionality
--wrap symbol
Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to __wrap_symbol. Any undefined reference to __real_symbol will be resolved to symbol. This can be used to provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wishes to call the system function, it should call __real_symbol. Here is a trivial example:
void *
__wrap_malloc (int c)
{
printf ("malloc called with %ld\n", c);
return __real_malloc (c);
}
This solution is nice but does not work for all compilers I guess.
The question is - which one are you using on your projects?
You have to draw a line to what to mock, and what to unit test. 100% unit tests coverage is not the ultimate goal.
If you really want to mock systam calls, the best is to put them in a wrapper (the first option in the question). Not one huge wrapper, but you should split them into several wrappers by functionality.
System calls are infrastructure
We wrap infra logic using a wrapper
Also design the wrapper such that there can be many wrappers based on context.
Also I agree with "BЈовић" 100% coverage is not the ultimate goal - balance it.
(1) example is incorrect about mock, maybe because you don't want to clarify what you are doing and your example doesn't show me what mocks what. Mocking is actually a practical exemplified use of polymorphism. People tend to wrap all things up in wrapper functions and then even in wrapper classes
IParam param=new ParamMock(xxx);
File file(param); // mocked
....
file.open(xxx)
(2) I don't know about it
(3) definitely it shows you know too much and spend too much effort for unit-testing. I always put in mind that unit-tests will be thrown away after all.
What development process are you following ?

What's the safest way to define short function name aliases in C++?

Suppose I have a class Utility in a file utility.h:
class Utility {
public:
static double longDescriptiveName(double x) { return x + 42; }
};
And then I find that I use the function longDescriptiveName(...) a LOT. So like an irresponsible C++ programmer that I am when I've had too much coffee, I create a new file utilitymacros.h and add the following there:
#define ldn Utility::longDescriptiveName
Now I include "utilitymacros.h" in any *.cpp where I use ldn(...) and my heart is filled with joy over how much more convinient it is to type 3 letters vs 28.
Question: Is there a safer (more proper) way of doing this than with #define?
I've noticed that I have to include "utilitymacros.h" after including boost headers, which I obviously don't like because it's a sign of clashes (though the Boost errors I get are not very clear as to what the clash is).
Clarification 1: On Code Readability
In case you might say that this negatively affects code readability, I assure you it does not, because it's a small set of functions that are used A LOT. An example that is widely know is stoi for stringToInteger. Another is pdf for probabilityDensityFunction, etc. So if I want to do the following, stoi is more readable in my opinion:
int x = stoi(a) + stoi(b) + stoi(c) + stoi(d);
Than:
int x = Utility::stringToInteger(a) + Utility::stringToInteger(b)
+ Utility::stringToInteger(c) + Utility::stringToInteger(d);
Or:
int x = Utility::stringToInteger(a);
x += Utility::stringToInteger(b);
x += Utility::stringToInteger(c);
x += Utility::stringToInteger(d);
Clarification 2: Editor Macro
I use Emacs as my IDE of choice and a Kinesis keyboard so you KNOW I use a ton of keyboard macros, custom keyboard shortcuts, as well as actually modifying what I see in the editor vs what's actually stored in the h/cpp file. But still, I feel like the simplicity and visual readability (as argued above) of using a function abbreviation in a few select cases really is the result I'm looking for (this is certainly subject to a degree).
Instead of macro, you could write inline function that forwards the call to the actual function:
inline double ldn(double x)
{
return Utility::longDescriptiveName(x);
}
That is certainly safer than macro.
You could use a function reference:
double (&ldn)(double) = Utility::longDescriptiveName;
How about configuring a snippit/macro/similar thing in your text editor? This way you only have to type ldn or something like that and the code doesn't have to run through the preprocessor risking difficult to find bugs later.
I don't know if this helps, but I think part of the problem may be the use of overly general namespaces (or class names, in this case), such as Utility.
If instead of Utility::stringToInteger, we had
namespace utility {
namespace type_conversion {
namespace string {
int to_int(const std::string &s);
}
}
}
Then the function could locally be used like this:
void local_function()
{
using namespace utility::type_conversion::string;
int sum = to_int(a) + to_int(b) + to_int(c) + to_int(d);
}
Analogously, if classes/structs and static functions are used (and there can be good reasons for this), we have something like
strut utility {
struct type_conversion {
struct string {
static int to_int(const std::string &s);
};
};
};
and the local function would look something like this:
void local_function()
{
typedef utility::type_conversion::string str;
int sum = str::to_int(a) + str::to_int(b)
+ str::to_int(c) + str::to_int(d);
}
I realize I am not telling you anything about syntax you didn't know already; it's more a reminder of the fact that the organization and structure of namespaces and classes itself plays an important role in making code more readable (and writable).
One alternative is to rename your function and put it in a namespace instead of a class, since it is static anyway. utility.h becomes
namespace Utility {
// long descriptive comment
inline double ldn(double x) { return x + 42; }
}
Then you can put using namespace Utility; in your client code.
I know there are lots of style guides out there saying short names are a bad thing, but I don't see the point of obeying some style and then circumventing it.
You can use alias template (since C++11).
using shortName = my::complicate::function::name;